python - 有效地将元组列表转换为具有相应总和的集合
问题描述
我有这样的清单:
x = [(('abc', 'def'), 1), (('foo', 'bar'), 0), (('def', 'abc'), 3)]
我想创建一个列表,其中包含唯一元素及其相应的总和,其中顺序无关紧要。我想要这样的列表:
[(('abc', 'def'), 4), (('foo', 'bar'), 0)]
在 python 中执行此操作的有效方法是什么?
与此不同,因为我在询问第一个参数是无序的元组的元组。
解决方案
你可以用collections.Counter
这个
from collections import Counter
c = Counter()
for k,v in x:
c[tuple(sorted(k))] += v
print(c)
# Counter({('abc', 'def'): 4, ('bar', 'foo'): 0})
print (list(c.items()))
# [(('abc', 'def'), 4), (('bar', 'foo'), 0)]