二维数组Python部分的列

时间:2017-06-16 15:40:20

标签: python arrays matrix sum

INPUT:

M = [[1,2,3],
    [1,2,3],
    [1,2,3]]

如何获取前两行中的列的总和并在数组M

中实现它

输出:

M = [[2,4,6],
    [1,2,3]]

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

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 assignment
  • [... for .. in ...]:python list comprehension
  • for a, b in ...:python tuple unpacking loop