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

Python 对二维列表的每个元素求和,python,python-3.x,Python,Python 3.x,我有这样一个二维列表: list1 = [[2,4,6,8,9],[8,9,10,12,15],[8,9,4,20,25]] 我想将每一行的每个元素与另一行相加,结果如下: outcome_list = [[10,13,16,20,24],[16,18,14,32,40],[10,13,20,28,34]] 我的代码是: d = len(list1) for i in range(0, d-1): list2 = list[i][:] + list[i+1][:] 但是它不起作

我有这样一个二维列表:

list1 = [[2,4,6,8,9],[8,9,10,12,15],[8,9,4,20,25]]
我想将每一行的每个元素与另一行相加,结果如下:

outcome_list = [[10,13,16,20,24],[16,18,14,32,40],[10,13,20,28,34]]
我的代码是:

d = len(list1) 

for i in range(0, d-1):
    list2 = list[i][:] + list[i+1][:]
但是它不起作用。

可以像这样做:

代码: 结果: 与列表一起使用:

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]]
from operator import add
[list(map(add, *p)) for p in zip(list1, list1[1:] + list1[:1])]
试试这个

d = len(list1) 

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

您可以通过压缩列表本身(但项目向右旋转)和
将对子列表映射到
操作符来对子列表进行配对。在列表中添加
方法:

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]]
from operator import add
[list(map(add, *p)) for p in zip(list1, list1[1:] + list1[:1])]
这将返回:

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


下面是使用itertools的另一种方法,它应该适用于列表1中的任意数量的列表:

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) ]

有了这个当我的列表1变得更大的代码产品重复的结果!!!!!!!我的列表1有40行,运行代码时,错误列表索引超出范围!!!!你知道吗?我不明白你在说什么。你能试着用另一种方式说吗?我的意思是,当和2元素除以2,然后打印结果列表=[[2,4,6],[8,10,12],[14,16,18],[14,16,18],现在我的结果应该是结果=[[5,7,9],[11,13,15],[8,10,12]],你可以这样做:
[[a+b在zip中为a,b(*p)]在zip中为p(list1,list1[1])+list1[:1]
otherList+=结果(也必须是列表的列表)
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) ]