列表列表的总和;返回总和清单 [英] Sum of list of lists; returns sum list
问题描述
让data = [[3,7,2],[1,4,5],[9,8,7]]
比方说,我想对列表中每个列表的索引元素求和,例如在矩阵列中添加数字以获得单个列表.我假设数据中的所有列表的长度都相等.
Let's say I want to sum the elements for the indices of each list in the list, like adding numbers in a matrix column to get a single list. I am assuming that all lists in data are equal in length.
print foo(data)
[[3,7,2],
[1,4,5],
[9,8,7]]
_______
>>>[13,19,14]
如何遍历列表列表而又不会出现索引超出范围的错误?也许lambda?谢谢!
How can I iterate over the list of lists without getting an index out of range error? Maybe lambda? Thanks!
推荐答案
您可以尝试以下方法:
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]
这使用zip
和*
的组合来解压缩列表,然后根据项目的索引对其进行压缩.然后,您可以使用列表推导来遍历相似索引的组,对其进行求和并返回其原始"位置.
This uses a combination of zip
and *
to unpack the list and then zip the items according to their index. You then use a list comprehension to iterate through the groups of similar indices, summing them and returning in their 'original' position.
希望更清楚一点,这是您遍历zip(*l)
时发生的事情:
To hopefully make it a bit more clear, here is what happens when you iterate through zip(*l)
:
In [13]: for i in zip(*l):
....: print i
....:
....:
(3, 1, 9)
(7, 4, 8)
(2, 5, 7)
对于长度不相等的列表,可以将itertools.izip_longest
与fillvalue
的0
一起使用-这基本上用0
填充缺失的索引,从而使您可以对所有列"求和:
In the case of lists that are of unequal length, you can use itertools.izip_longest
with a fillvalue
of 0
- this basically fills missing indices with 0
, allowing you to sum all 'columns':
In [1]: import itertools
In [2]: l = [[3,7,2],[1,4],[9,8,7,10]]
In [3]: [sum(i) for i in itertools.izip_longest(*l, fillvalue=0)]
Out[3]: [13, 19, 9, 10]
在这种情况下,这是在izip_longest
上进行迭代的样子:
In this case, here is what iterating over izip_longest
would look like:
In [4]: for i in itertools.izip_longest(*l, fillvalue=0):
...: print i
...:
(3, 1, 9)
(7, 4, 8)
(2, 0, 7)
(0, 0, 10)
这篇关于列表列表的总和;返回总和清单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!