首頁  >  文章  >  後端開發  >  如何根據特定鍵在 Python 中有效地將資料分組?

如何根據特定鍵在 Python 中有效地將資料分組?

Linda Hamilton
Linda Hamilton原創
2024-10-27 00:29:02804瀏覽

How do you efficiently group data in Python based on a specific key, and what are the different methods available for this task?

Python Group By

按鍵將資料分組

在Python 中,按特定鍵將資料分組涉及基於公共屬性來組織專案.這可以透過各種方法來實現,為大型資料集提供有效的解決方案。讓我們探索如何有效地將資料分組。

使用 defaultdict 的高效分組技術

考慮一個場景,我們有一組資料對,目標是根據它們的類型對它們進行分組。為了實現這一點,我們可以利用 collections.defaultdict 類別。它會建立一個字典,其中缺少的鍵會自動使用預設值進行初始化,從而允許我們將項目附加到這些鍵。

<code class="python">from collections import defaultdict

input = [
    ('11013331', 'KAT'),
    ('9085267', 'NOT'),
    ('5238761', 'ETH'),
    ('5349618', 'ETH'),
    ('11788544', 'NOT'),
    ('962142', 'ETH'),
    ('7795297', 'ETH'),
    ('7341464', 'ETH'),
    ('9843236', 'KAT'),
    ('5594916', 'ETH'),
    ('1550003', 'ETH'),
]

res = defaultdict(list)
for v, k in input:
    res[k].append(v)

print([{ 'type': k, 'items': v } for k, v in res.items()])</code>

輸出:

[{'items': ['9085267', '11788544'], 'type': 'NOT'}, {'items': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 'type': 'ETH'}, {'items': ['11013331', '9843236'], 'type': 'KAT'}]

使用 itertools.groupby

另一種方法涉及使用 itertools.groupby。此函數需要預先對輸入進行排序。它產生指定鍵的值相同的連續元素組。

<code class="python">import itertools
from operator import itemgetter

sorted_input = sorted(input, key=itemgetter(1))
groups = itertools.groupby(sorted_input, key=itemgetter(1))

print([{ 'type': k, 'items': [x[0] for x in v]} for k, v in groups])</code>
輸出:

[{'items': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 'type': 'ETH'}, {'items': ['11013331', '9843236'], 'type': 'KAT'}, {'items': ['9085267', '11788544'], 'type': 'NOT'}]
維護字典中的插入順序

之前Python 3.7,字典不保留插入順序。為了解決這個問題,可以使用 collections.OrderedDict 來維護鍵值對的順序。

<code class="python">from collections import OrderedDict

res = OrderedDict()
for v, k in input:
    if k in res:
        res[k].append(v)
    else:
        res[k] = [v]

print([{ 'type': k, 'items': v } for k, v in res.items()])</code>
但是,在 Python 3.7 及更高版本中,常規字典會保留插入順序,因此不需要 OrderedDict。

以上是如何根據特定鍵在 Python 中有效地將資料分組?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn