简体   繁体   English

对二维列表python的每个元素求和

[英]sum every element of 2 dimensional list python

I have a 2 dimensional list like this : 我有一个二维列表,像这样:

list1 = [[2,4,6,8,9],[8,9,10,12,15],[8,9,4,20,25]]

I want to sum every element of every row with another row and outcome is like this: 我想将每一行的每个元素与另一行相加,结果是这样的:

outcome_list = [[10,13,16,20,24],[16,18,14,32,40],[10,13,20,28,34]]

My code is this: 我的代码是这样的:

d = len(list1) 

for i in range(0, d-1):
    list2 = list[i][:] + list[i+1][:]

But it does not work. 但这行不通。

That can be done like: 可以这样完成:

Code: 码:

list1 = [[2, 4, 6, 8, 9], [8, 9, 10, 12, 15], [8, 9, 4, 20, 25]]

print([[sum(l) for l in zip(list1[i], list1[(i+1) % len(list1)])]
       for i in range(len(list1))])

Results: 结果:

[[10, 13, 16, 20, 24], [16, 18, 14, 32, 40], [10, 13, 10, 28, 34]]

Use zip() with a list-comprehension: zip()与list-comprehension一起使用:

list1 = [[2,4,6,8,9],[8,9,10,12,15],[8,9,4,20,25]]

list1 = list1 + [list1[0]]
print([list(map(lambda x: sum(x), zip(x, y))) for x, y in zip(list1, list1[1:])])

# [[10, 13, 16, 20, 24], [16, 18, 14, 32, 40], [10, 13, 10, 28, 34]]

Try this 尝试这个

d = len(list1) 

for i in range(0, d-1):
    list2 = [a + b for a,b in zip(list[i],list[i+1])]

You can pair the sub-lists by zipping the list with itself but with the items rotated to the right, and map the pairs to the operator.add method in a list comprehension: 您可以通过将列表本身压缩,但将项目向右旋转来对子列表进行配对,然后将对map到列表理解中的operator.add方法:

from operator import add
[list(map(add, *p)) for p in zip(list1, list1[1:] + list1[:1])]

This returns: 返回:

[[10, 13, 16, 20, 24], [16, 18, 14, 32, 40], [10, 13, 10, 28, 34]]

Use numpy.roll : 使用numpy.roll

In [1]: import numpy as np

In [2]: a = np.array([[2,4,6,8,9],[8,9,10,12,15],[8,9,4,20,25]])

In [3]: a + np.roll(a, -1, axis=0)
Out[3]:
array([[10, 13, 16, 20, 24],
       [16, 18, 14, 32, 40],
       [10, 13, 10, 28, 34]])

Here's one more way to do it using itertools which should work for any number of lists in list1: 这是使用itertools的另一种方法,该工具应适用于list1中的任意数量的列表:

from itertools import combinations
list1   = [[2,4,6,8,9],[8,9,10,12,15],[8,9,4,20,25]]
outcome = [ list(map(sum,zip(*rows))) for rows in combinations(list1,2) ]

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

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