[英]How to sum up tuples values within a list in defaultdict using Counter?
I have a defaultdict
which groups values as a list of tuples. 我有一个
defaultdict
将值分组为元组列表。 I'd like to add values of each key using Counter
. 我想使用
Counter
添加每个键的值。
So, the question is how to tranform this: 因此,问题是如何对此进行转换:
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)])
])
into this: 到这个:
[
'Key_One': Counter({'1': 23, '5': 1})
'Key_Two': Counter({'1': 53})
]
Using collections.defaultdict
and a simple iteration 使用
collections.defaultdict
和一个简单的迭代
Ex: 例如:
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)
Output: 输出:
{'Key_One': defaultdict(<class 'int'>, {'1': 23, '5': 1}), 'Key_Two': defaultdict(<class 'int'>, {'1': 53})}
Using collections.Counter
使用
collections.Counter
Ex: 例如:
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)
Output: 输出:
{'Key_One': Counter({'1': 23, '5': 1}), 'Key_Two': Counter({'1': 53})}
Using Counter and defaultdict. 使用Counter和defaultdict。 Python 3.6.7
的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)
Output: 输出:
{'Key_One': Counter({'1': 23, '5': 1}), 'Key_Two': Counter({'1': 53})}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.