简体   繁体   English

合并嵌套列表的第一个元素,然后对第二个元素求和

[英]Combining first elements of nested lists and summing the second elements

I have a list like this: 我有一个这样的清单:

list = [["r", 200], ["c,", 0.22], ["r", 5000]]

How can I combine the tuples with the same first item so that the result is like this: 如何将元组与相同的第一项组合在一起,以便结果如下所示:

list = [["r", 5200], ["c", 0.22]]

Is there some sophisticated way of doing this? 有一些复杂的方法吗? The order of tuples doesn't matter. 元组的顺序无关紧要。

Thanks 谢谢

You can use collections.defaultdict : 您可以使用collections.defaultdict

>>> from collections import defaultdict
>>> t = [["r", 200], ["c,", 0.22], ["r", 5000]]
>>> d = defaultdict(int)
>>> for i, j in t:
...     d[i] += j
... 
>>> print d.items()
[('r', 5200), ('c,', 0.22)]

By the way, don't name a list list . 顺便说一句,不要命名列表list It will override the built-in type. 它将覆盖内置类型。

With use of built-in functions: 使用内置功能:

lst = [["r", 200], ["c,", 0.22], ["r", 5000]]
res={}
for k,v in lst:
  res[k]=res.get(k, 0) + v
res
# {'r': 5200, 'c,': 0.22}

To get the result in the original type: 要获得原始类型的结果:

[[k, v] for k,v in res.iteritems()]
# [['r', 5200], ['c,', 0.22]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM