簡體   English   中英

如何使用Counter在defaultdict中匯總列表中的元組值?

[英]How to sum up tuples values within a list in defaultdict using Counter?

我有一個defaultdict將值分組為元組列表。 我想使用Counter添加每個鍵的值。

因此,問題是如何對此進行轉換:

dict_items([
    ('Key_One', [('1', 7), ('1', 2), ('1', 2), ('1', 12), ('5', 1)]),
    ('Key_Two', [('1', 13), ('1', 9), ('1', 7), ('1', 12), ('1', 2), ('1', 10)])
])

到這個:

[
    'Key_One': Counter({'1': 23, '5': 1})
    'Key_Two': Counter({'1': 53})
]

使用collections.defaultdict和一個簡單的迭代

例如:

from collections import defaultdict

d = dict([
    ('Key_One', [('1', 7), ('1', 2), ('1', 2), ('1', 12), ('5', 1)]),
    ('Key_Two', [('1', 13), ('1', 9), ('1', 7), ('1', 12), ('1', 2), ('1', 10)])
])

result = {}
for k, v in d.items():
    temp = defaultdict(int)
    for m, n in v:
        temp[m] += n
    result[k] = temp
print(result)

輸出:

{'Key_One': defaultdict(<class 'int'>, {'1': 23, '5': 1}), 'Key_Two': defaultdict(<class 'int'>, {'1': 53})}

使用collections.Counter

例如:

from collections import Counter

d = dict([
    ('Key_One', [('1', 7), ('1', 2), ('1', 2), ('1', 12), ('5', 1)]),
    ('Key_Two', [('1', 13), ('1', 9), ('1', 7), ('1', 12), ('1', 2), ('1', 10)])
])

result = {}
for k, v in d.items():
    temp = Counter()
    for m, n in v:
        temp.update(Counter({m:n}))
    result[k] = temp
print(result)

輸出:

{'Key_One': Counter({'1': 23, '5': 1}), 'Key_Two': Counter({'1': 53})}

使用Counter和defaultdict。 的Python 3.6.7

from collections import Counter
from collections import defaultdict

a = dict([
    ('Key_One', [('1', 7), ('1', 2), ('1', 2), ('1', 12), ('5', 1)]),
    ('Key_Two', [('1', 13), ('1', 9), ('1', 7), ('1', 12), ('1', 2), ('1', 10)])
          ])

l = {}
for i in a:
    output = defaultdict(int)
    for k, v in a[i]:
        output[k] += v
    l.update({i: Counter(dict(output.items()))})

print(l)

輸出:

{'Key_One': Counter({'1': 23, '5': 1}), 'Key_Two': Counter({'1': 53})}

暫無
暫無

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

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