[英]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.