0

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

OUTPUT:

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

2 Answers 2

1

Use 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]])
Sign up to request clarification or add additional context in comments.

Comments

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]]

Things to google to understand this:

  • M[:2] =: python slice assignment
  • [... for .. in ...]: python list comprehension
  • for a, b in ...: python tuple unpacking loop

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.