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中执行此操作的有效方法是什么?
它与此不同,因为我在询问元组的元组,其中第一个参数是无序的.
你可以用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)
| 归档时间: |
|
| 查看次数: |
300 次 |
| 最近记录: |