Skip to content Skip to sidebar Skip to footer

Multiplication Between 2 Lists

i have 2 lists a=[[2,3,5],[3,6,2],[1,3,2]] b=[4,2,1] i want the output to be: c=[[8,12,20],[6,12,4],[1,3,2]] At present i am using the following code but its problem is that the

Solution 1:

Use zip() to combine each list:

a=[[2,3,5],[3,6,2],[1,3,2]]
b=[4,2,1]

[[m*n for n in second] for m, second in zip(b,a)]

Solution 2:

You can use numpy :

>>> import numpy as np
>>> a=np.array([[2,3,5],[3,6,2],[1,3,2]])
>>> b=np.array([4,2,1])

>>> a*np.vstack(b)
array([[ 8, 12, 20],
       [ 6, 12,  4],
       [ 1,  3,  2]])

Or as @csunday95 suggested as a more optimized way you can use transpose instead of vstack :

>>> (a.T*b).T 
array([[ 8, 12, 20],
       [ 6, 12,  4],
       [ 1,  3,  2]])

Solution 3:

This may not be faster, but it's a neater way of doing it :)

c = []
b_len = len(b)
for i in range(len(a)):
    b_multiplier = b[i%b_len]
    c.append([x*b_multiplier for x in a[i]])

Alternate short way now I've actually read the question properly and realised a and b are the same length:

c = [[x*b[i] for x in a[i]]for i in range(len(a))]  

Post a Comment for "Multiplication Between 2 Lists"