簡體   English   中英

Python:如何在字典中聚合和計算相同的值

[英]Python: How to aggregate and count identical values in a Dictionary

我正在使用 Python 集合中的 defaultdict:

from collections import defaultdict
data = defaultdict(list)

在字典中,我有一組鍵/列表。 例子:

{1: [1, 6, 3, 4, 5], 2: [1, 3, 2, 4, 5], 3: [1, 6, 3, 4, 5]})

我正在尋找一種方法來計算在字典中找到每個列表(相同的順序和內容)的次數。 基本上,我需要用計數器匯總每個列表。 例如,組合 [1, 6, 3, 4, 5] 被找到 2 次。 是否有任何幫助類/函數可以做到這一點? 除此之外,我只需在字典中創建一個雙 for 循環。 謝謝!

H = {1: [1, 6, 3, 4, 5], 2: [1, 3, 2, 4, 5], 3: [1, 6, 3, 4, 5]}
occurences = dict()
for i in H.keys() :
    k = 0
    for j in H.keys():
        if H[j] == H[i] :
            k += 1 
    if i not in occurences.keys():
        occurences[i] = k

使用collections.Counter

>>> from collections import Counter
>>> d = {1: [1, 6, 3, 4, 5], 2: [1, 3, 2, 4, 5], 3: [1, 6, 3, 4, 5]}
>>> print(Counter(tuple(l) for l in d.values())
Counter({(1, 6, 3, 4, 5): 2, (1, 3, 2, 4, 5): 1})

您必須將列表轉換為元組,因為計數器無法計算不可散列(可變)類型。

嘗試這個:

from collections import Counter
data = defaultdict(list, {1: [1, 6, 3, 4, 5], 2: [1, 3, 2, 4, 5], 3: [1, 6, 3, 4, 5]})
c = Counter(map(tuple, data.values()))

print(c)

Counter({(1, 6, 3, 4, 5): 2, (1, 3, 2, 4, 5): 1})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM