2017-06-16 58 views
0

INPUT:總和列

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

如何採取列的總和的兩個第一行和所述陣列中實施它中號

OUTPUT:

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

歡迎的StackOverflow!如果您遇到特定的編程問題,我們將很樂意爲您提供幫助,但我們不在這裏爲您編寫代碼。請參閱[我如何問一個好問題?](https://stackoverflow.com/help/how-to-ask)和[我可以問什麼問題?](https://stackoverflow.com/help /切合主題)。 –

回答

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
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] =:蟒蛇片分配
  • [... for .. in ...]:Python列表理解
  • for a, b in ...:蟒蛇元組拆包環