我在python中有字典
d = {(2,4):40,(1,2,4):8}
在这个dict键中是元组, 值是元组中每个元素的计数
我需要输出1个字典作为 所有元组中值的总数
out={2:48,4:48,1:8}
我给出的例子是小字典,但我有非常大的字典,所以时间复杂性起着关键作用 有人可以帮助我吗?
答案 0 :(得分:2)
您可以一次完成此操作,只需遍历键并添加相应的值即可。您可以使用collections.Counter
或您喜欢的任何类似dict / dict的容器:
>>> origin = {(2,4):40,(1,2,4):8}
>>> from collections import Counter
>>> counts = Counter()
>>> for k, v in origin.items(): # python 2 use .iteritems()
... for x in k:
... counts[x] += v
...
>>> counts
Counter({2: 48, 4: 48, 1: 8})
答案 1 :(得分:1)
可以利用多个Counters
的功能轻松总结以创建一些简洁的单行,但他们的表现无法与juanpa's explicit loop approach竞争(原始dict
的时间):
from collections import Counter
from operator import add
from functools import reduce
# 1
out = sum((Counter({x: v for x in k}) for k, v in d.items()), Counter())
# timeit: 16.2
# 2
out = reduce(add, (Counter({x: v for x in k}) for k, v in d.items()))
# timeit: 10.8
# 3
# juanpa's approach
# timeit: 3.7
答案 2 :(得分:0)
Dict = {(2,4):40,(1,2,4):8}
Out={}
for k,v in Dict.items():
for i in k:
if i in Out:
Out[i] += v
else:
Out[i] = v
print(Out)
{2: 48, 4: 48, 1: 8}