[英]sum columns of part of 2D array Python
INPUT: 输入:
M = [[1,2,3],
[1,2,3],
[1,2,3]]
how take the sum of the columns in the two first rows and implement it in the array M 如何获取前两行中各列的总和并在数组M中实现
OUTPUT: 输出:
M = [[2,4,6],
[1,2,3]]
Use numpy.add.reduceat
: 使用
numpy.add.reduceat
:
import numpy as np
M = [[1,2,3],
[1,2,3],
[1,2,3]]
np.add.reduceat(M, [0, 2])
# indices [0,2] splits the list into [0,1] and [2] to add them separately,
# you can see help(np.add.reduceat) for more
# array([[2, 4, 6],
# [1, 2, 3]])
M = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
M[:2] = [[a + b for a, b in zip(M[0], M[1])]]
print(M) # [[5, 7, 9], [7, 8, 9]]
Things to google to understand this: 谷歌了解这一点:
M[:2] =
: python slice assignment M[:2] =
:python slice分配 [... for .. in ...]
: python list comprehension [... for .. in ...]
:python列表理解 for a, b in ...
: python tuple unpacking loop for a, b in ...
:python tuple unpacking loop
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.