有效地将元组列表转换为具有相应总和的集合

shi*_*k01 3 python list python-3.x

我有这样的列表:

x = [(('abc', 'def'), 1), (('foo', 'bar'), 0), (('def', 'abc'), 3)]
Run Code Online (Sandbox Code Playgroud)

我想创建一个列表,其中包含唯一的元素及其相应的总和,其中顺序无关紧要.我想要这样的列表:

[(('abc', 'def'), 4),  (('foo', 'bar'), 0)]
Run Code Online (Sandbox Code Playgroud)

在python中执行此操作的有效方法是什么?

它与不同,因为我在询问元组的元组,其中第一个参数是无序的.

Sun*_*tha 5

你可以用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)]
Run Code Online (Sandbox Code Playgroud)

  • 使用`c [k] + v`而不是`.update`.不要将`.update`用于单个键值对.注意,这(非常低效)创建了一个无用的字典. (2认同)