Python 列表列表的总和;返回总和列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13783315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 09:35:39  来源:igfitidea点击:

Sum of list of lists; returns sum list

pythonlistmatrixsum

提问by Albert

Let data = [[3,7,2],[1,4,5],[9,8,7]]

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]

How can I iterate over the list of lists without getting an index out of range error? Maybe lambda? Thanks!

如何遍历列表列表而不会出现索引超出范围错误?也许拉姆达?谢谢!

采纳答案by RocketDonkey

You could try this:

你可以试试这个:

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]

This uses a combination of zipand *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*解压的列表,然后根据自己的索引压缩的项目。然后,您使用列表推导式遍历相似索引的组,将它们相加并返回到它们的“原始”位置。

To hopefully make it a bit more clear, here is what happens when you iterate through zip(*l):

为了希望让它更清楚一点,以下是您迭代时会发生的情况zip(*l)

In [13]: for i in zip(*l):
   ....:     print i
   ....:     
   ....:     
(3, 1, 9)
(7, 4, 8)
(2, 5, 7)

In the case of lists that are of unequal length, you can use itertools.izip_longestwith a fillvalueof 0- this basically fills missing indices with 0, allowing you to sum all 'columns':

对于长度不等的列表,您可以使用itertools.izip_longesta fillvalueof 0- 这基本上用 填充缺失的索引0,允许您对所有“列”求和:

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]

In this case, here is what iterating over izip_longestwould look like:

在这种情况下,以下是迭代的izip_longest样子:

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)

回答by Marius

This does depend on your assumption that all the inner lists (or rows) are of the same length, but it should do what you want:

这确实取决于您假设所有内部列表(或行)的长度相同,但它应该做您想做的:

sum_list = []

ncols = len(data[0])

for col in range(ncols):
    sum_list.append(sum(row[col] for row in data))


sum_list
Out[9]: [13, 19, 14]

回答by Theuni

For any matrix (or other ambitious numerical) operations I would recommend looking into NumPy.

对于任何矩阵(或其他雄心勃勃的数值)运算,我建议研究 NumPy。

The sample for solving the sum of an array along the axis shown in your question would be:

沿着您的问题中显示的轴求解数组总和的示例是:

>>> from numpy import array
>>> data = array([[3,7,2],
...     [1,4,5],
...     [9,8,7]])
>>> from numpy import sum
>>> sum(data, 0)
array([13, 19, 14])

Here's numpy's documentation for its sum function: http://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html#numpy.sum

这是 numpy 的 sum 函数文档:http: //docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html#numpy.sum

Especially the second argument is interesting as it allows easily specify what should be summed up: all elements or only a specific axis of a potentially n-dimensional array(like).

特别是第二个参数很有趣,因为它可以轻松指定应总结的内容:所有元素或仅潜在 n 维数组(如)的特定轴。

回答by Nathan

>>> data = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
>>> for column in enumerate(data[0]):
...     count = sum([x[column[0]] for x in data])
...     print 'Column %s: %d' % (column[0], count)
... 
Column 0: 3
Column 1: 6
Column 2: 9

回答by MySchizoBuddy

This will give you the sum for each sublist

这将为您提供每个子列表的总和

data = [[3,7,2],[1,4],[9,8,7,10]]
list(map(sum, data))
[12, 5, 34]

If you want to sum over all elements and get just one sum then use this

如果你想对所有元素求和并只得到一个总和,那么使用这个

data = [[3,7,2],[1,4],[9,8,7,10]]
sum(sum(data, []))
51

回答by user3481919

def sum(L):
res = list()
for j in range(0,len(L[0])):
    tmp = 0
    for i in range(0,len(L)):
        tmp = tmp + L[i][j]
    res.append(tmp)
return res

回答by Daniel Marmelshtein

numArr = [[12, 4], [1], [2, 3]]

sumArr = 0

sumArr = sum(sum(row) for row in numArr)

print(sumArr) 

the answere: 22
numArr = [[12, 4], [1], [2, 3]]

sumArr = 0

sumArr = sum(sum(row) for row in numArr)

print(sumArr) 

the answere: 22

what I did: when you do "for" like this for example: [row.append(1) for row in numArr] the list will change to: [[12, 4, 1], [1, 1], [2, 3, 1]] I used the function sum() from python, the function takes the list and do iteration on it and bring the sum of all the numbers in the list. when I did sum(sum()) I got the sum of all the lists in the big list.

我做了什么:当你像这样执行“for”时,例如:[row.append(1) for row in numArr] 列表将更改为:[[12, 4, 1], [1, 1], [2 , 3, 1]] 我使用了 python 中的 sum() 函数,该函数获取列表并对其进行迭代,并得出列表中所有数字的总和。当我做 sum(sum()) 时,我得到了大列表中所有列表的总和。

回答by Mokogwu Chiedu

This solution assumes a square matrix and uses two for loops to loop over the columns and rows, adding column-wise in the process. The result is returned in a list.

此解决方案假设一个方阵,并使用两个 for 循环来循环列和行,在此过程中逐列添加。结果以列表形式返回。

def foo(data):
    # initialise length of data(n) and sum_of_col variable 
    n = len(data)
    sum_of_col = []

    # iterate over column
    for col_i in range(n):
        # column sum
        col_count = 0;

        #iterate over row
        for row_i in range(n):
            col_count += data[row_i][col_i]

        # append sum of column to list    
        sum_of_col.append(col_count)

    return sum_of_col

回答by pablokimon

The simplest solution that will sum a list of lists of different or identical lengths is:

对不同或相同长度的列表求和的最简单解决方案是:

total = 0
for d in data:
    total += sum(d)

Once you understand list comprehension you could shorten it:

一旦你理解了列表理解,你就可以缩短它:

sum([sum(d) for d in data])

回答by wwii

For the case that the data is a list of lists of strings. Sum or concatenate a list of lists of strings elementwise.

对于数据是字符串列表列表的情况。按元素求和或连接字符串列表的列表。

>>> a = [list('abc'),list('def'),list('tyu')]
>>> a
[['a', 'b', 'c'], ['d', 'e', 'f'], ['t', 'y', 'u']]
>>> [''.join(thing) for thing in zip(*a)]
['adt', 'bey', 'cfu']
>>>