[英]sum columns of part of 2D array Python
輸入:
M = [[1,2,3],
[1,2,3],
[1,2,3]]
如何獲取前兩行中各列的總和並在數組M中實現
輸出:
M = [[2,4,6],
[1,2,3]]
使用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]]
谷歌了解這一點:
M[:2] =
:python slice分配 [... for .. in ...]
:python列表理解 for a, b in ...
:python tuple unpacking loop
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.