繁体   English   中英

2D数组Python的一部分的总和列

[英]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.

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