0

I have the following list:

ls = [[1,2,3], [3,4] , [5] , [7,8], [23], [90, 81]]

This is my numpy array:

array([[    1,     0,     4,     3],
       [   10,   100,  1000, 10000]])

I need to multiply the values in the second row of my array by the length of the list in ls which is at the index of the corresponding number in the first row:

10 * len(ls[1]) & 100 * len(ls[0]) etc..

The objective output would be this array:

array([[    1,     0,     4,     3],
       [   20,   300,  1000, 20000]])

Any efficient way doing this?

1 Answer 1

3

Use list comprehesion to find lengths and multiply it with 2nd row of array as:

ls = [[1,2,3], [3,4] , [5] , [7,8]]
arr = np.array([[    1,     0,     2,     3],
                [   10,   100,  1000, 10000]])

arr[1,:] = arr[1,:]*([len(l) for l in ls])

arr
array([[    1,     0,     2,     3],
       [   30,   200,  1000, 20000]])

EDIT :

arr[1,:] = arr[1,:]*([len(ls[l]) for l in arr[0,:]])

arr
array([[    1,     0,     2,     3],
       [   20,   300,  1000, 20000]])
Sign up to request clarification or add additional context in comments.

1 Comment

This answer it not correct. Compare your output with by objective output. Maybe I have formed my question not clearly. Instead of 30, is should be 20, since the corresponding value in the first row is 1. Thus, 10 * len(ls[1]) = 20 and not 30

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.