Shubham Sharda
Shubham Sharda

Reputation: 693

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 computation time is very high as the number of values in my list are very large.The first list of list has 1000 list in which each list has 10000 values and the second list has 1000 values.Therefore the computation time is a problem.I want a new idea in which computation time is less.The present code is:

a=[[2,3,5],[3,6,2],[1,3,2]]
b=[4,2,1]
c=[]
s=0
for i in b:
    c1=[]
    t=0
    s=s+1
    for j in a:
        t=t+1
        for k in j:
            if t==s:
                m=i*k
                c1.append(m)
    c.append(c1)
print(c)

Upvotes: 0

Views: 183

Answers (3)

Peter
Peter

Reputation: 3495

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

Upvotes: -1

Kasravnd
Kasravnd

Reputation: 107287

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

Upvotes: 4

TigerhawkT3
TigerhawkT3

Reputation: 49318

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

Upvotes: 4

Related Questions