目录:

1. 嵌套列表对应位置元素相加 (add the corresponding elements of nested list)

2. 多个列表对应位置相加(add the corresponding elements of several lists) 

3. 列表中嵌套元组对应位置相加 (python sum corresponding position in list neseted tuple)

 

内容:

1. 嵌套列表对应位置元素相加 (add the corresponding elements of nested list)

https://stackoverflow.com/questions/11280536/how-can-i-add-the-corresponding-elements-of-several-lists-of-numbers

方法1:

>>> lis=[[1,2,3,4,5],[2,3,4,5,6],[3,4,5,6,7]]
>>> [sum(x) for x in zip(*lis)]
[6, 9, 12, 15, 18] 

方法2:

>>> seq = np.array([
... [1,2,3,4,5],
... [2,3,4,5,6],
... [3,4,5,6,7]])
>>> np.sum(seq,axis=0)
array([ 6,  9, 12, 15, 18])

 

2. 多个列表对应位置相加(add the corresponding elements of several lists)  

https://stackoverflow.com/questions/11280536/how-can-i-add-the-corresponding-elements-of-several-lists-of-numbers

方法1: 

a = [1,2,3,4,5]
b = [2,3,4,5,6]
c = [3,4,5,6,7]
[sum(n) for n in zip(*[a, b, c])]

方法2:

>>> seq = np.array([
... [1,2,3,4,5],
... [2,3,4,5,6],
... [3,4,5,6,7]])
>>> np.sum(seq,axis=0)
array([ 6,  9, 12, 15, 18])

 

3. 列表中嵌套元组对应位置相加 (python sum corresponding position in list neseted tuple)

https://stackoverflow.com/questions/14180866/sum-each-value-in-a-list-of-tuples

方法1:

l = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 0)]
[sum(x) for x in zip(*l)]
[25, 20]

方法2:

map(sum, zip(*l))
[25, 20]

 

4 .

 

12-27 06:59