Home > Software design >  How to add value to a nested listed based on another list?
How to add value to a nested listed based on another list?

Time:09-17

I am not sure if the title makes sense but I have two lists:

a = [[8, 23, 45, 12, 78, 58], [2,3,4,1,5,4], [6, 7, 6, 9, 5, 8] , [1, 2, 4, 7, 8]]
b = [1, 0 , 1 , 2]

I want to try to multiply all of a[0] with b[0] and repeat this for all the others. Thus, have an output like:

[8,23, 45, 12, 78, 58], [0, 0, 0, 0, 0, 0], [6, 7, 6, 9, 8], [2, 4, 8, 14, 16]

I tried using for loop with nested loop but I end up multiply all of b with all of a. For example, I get:

8
23
45
12
78
58
0
0
0
0
0
6

and so on.

Is it possible to do with for loops? or Is there another way I should consider doing it?

CodePudding user response:

You can use a loop comprehension:

[[b[i]*v for v in suba] for i,suba in enumerate(a)]

output:

[[8, 23, 45, 12, 78, 58], [0, 0, 0, 0, 0, 0], [6, 7, 6, 9, 5, 8], [2, 4, 8, 14, 16]]

CodePudding user response:

You can use numpy.reshape(1,-1) and * like below:

a = np.array([
              np.array([8, 23, 45, 12, 78, 58]), 
              np.array([2,3,4,1,5,4]), 
              np.array([6, 7, 6, 9, 5, 8]) , 
              np.array([1, 2, 4, 7, 8])
])
b = np.array([1, 0 , 1 , 2]).reshape(1,-1)
a*b

output:

array([[array([ 8, 23, 45, 12, 78, 58]), array([0, 0, 0, 0, 0, 0]),
        array([6, 7, 6, 9, 5, 8]), array([ 2,  4,  8, 14, 16])]],
      dtype=object)

CodePudding user response:

With loops and enumerate (to get the index of list items)

a = [[8, 23, 45, 12, 78, 58], [2,3,4,1,5,4], [6, 7, 6, 9, 5, 8] , [1, 2, 4, 7, 8]]
b = [1, 0 , 1 , 2]

c = [] # output list
for idx, val in enumerate(b):
    d=[]
    for i in a[idx]:
        d.append(i*val)
    c.append(d)
print(c)

output

[[8, 23, 45, 12, 78, 58], [0, 0, 0, 0, 0, 0], [6, 7, 6, 9, 5, 8], [2, 4, 8, 14, 16]]

CodePudding user response:

If you want to see how to do this with a for loop you can do:

result = []
for i in range(len(b)):
  result.append([b[i] * num for num in a[i]])

if you print result you get:

[[8, 23, 45, 12, 78, 58], [0, 0, 0, 0, 0, 0], [6, 7, 6, 9, 5, 8], [2, 4, 8, 14, 16]]
  • Related