1

In python numpy:

A = [[1,2,3],[4,5,6],[7,8,9]]
b = [2,3,5]

want [1,2,3] -2, [4,5,6]-3, [7,8,9] -5

e.g. ideal result:

[[-1,0,1],[1,2,3],[2,3,4]]

any way solve this without loop?

1
  • 2
    Where are you using numpy? These are all just python lists. Commented Jul 17, 2019 at 14:27

3 Answers 3

3

You have not used Numpy at all. It is pretty easy with that. You need to add an extra dimension to b with None or numpy.newaxis and then subtract.

import numpy
A = numpy.array([[1,2,3],[4,5,6],[7,8,9]])
b = numpy.array([2,3,5])

c= A-b[:,None]

print(c)

Output:

[[-1  0  1]
 [ 1  2  3]
 [ 2  3  4]]
Sign up to request clarification or add additional context in comments.

1 Comment

this doesn't use loops unlike the other answers
0
for i in range(0, len(A)):
    cur_arr = A[i]
    for j in range(0, len(cur_arr)):
        cur_arr[j] = cur_arr[j] - B[j]

Comments

0

Using pure python you are going to need a for loop somewhere.

A_L = [[1,2,3],[4,5,6],[7,8,9]]
B_L = [2,3,5]

sub = lambda a, b : [[x - B for x in A] for A, B in zip(a,b)]

c = sub(A_L,B_L)
print(c)

Outputs: [[-1, 0, 1], [1, 2, 3], [2, 3, 4]]

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.