简体   繁体   English

元组列表的总和列表

[英]Sum list of list of tuples

I found that summing a list of list of number is: 我发现总结一个列表列表是:

In [9]: l = [[3,7,2],[1,4,5],[9,8,7]]
In [10]: [sum(i) for i in zip(*l)]
Out[10]: [13, 19, 14]

However I have been struggling to find a way to sum a list of list of tuples to result in a list of tuples 但是我一直在努力寻找一种方法来对元组列表进行求和以得到元组列表

In [9]: l = [[(1, 1), (1, 1), (1, 1)],[(2, 2), (2, 2), (2, 2)]]
In [10]: [(sum(i[0]), sum(i[1])) for i in zip(*l)] #Did not work

This is my desired output: 这是我想要的输出:

Out[10]: [(3, 3), (3, 3), (3, 3)]

Thanks! 谢谢!

You can use a tuple comprehension within a list comprehension: 您可以在列表理解中使用tuple理解:

L = [[(1, 1), (1, 1), (1, 1)], [(2, 2), (2, 2), (2, 2)]]

res = [tuple(sum(j) for j in zip(*i)) for i in zip(*L)]

[(3, 3), (3, 3), (3, 3)]

Or use map for a more functional alternative: 或者使用map来获得更多功能:

res = [tuple(map(sum, zip(*i))) for i in zip(*L)]

For larger lists, you may wish to consider a 3rd party library such as NumPy where, in NumPy terminology, you need only sum over a specified axis: 对于较大的列表,您可能希望考虑第三方库,例如NumPy,在NumPy术语中,您只需要在指定的轴上求和:

import numpy as np

A = np.array(L)

res = A.sum(axis=0)

array([[3, 3],
       [3, 3],
       [3, 3]])

You could flatten the iterable recursively first 您可以先递归地展平迭代

>>> import collections
>>> 
>>> def flatten(l):
...     for el in l:
...         if isinstance(el, collections.Iterable) and not isinstance(el, str):
...             for sub in flatten(el):
...                 yield sub
...         else:
...             yield el
... 
>>> sum(flatten(l))
18

See this link for more details on flatten . 有关flatten更多详细信息,请参阅此链接

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

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