繁体   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