pheel09
pheel09

Reputation: 17

Iterating over two lists and resulting in a third one

Does anyone know how would be a iteration code to do this:

I give two initial lists (l1 and l2):

l1=[a,b,c], where a,b,c are numbers
l2=[i,j,k,w,z]

And then get a third one (l3; which has the same length of l1):

l3=[[a*i+a*j+a*k+a*w+a*z],[b*i+b*j+b*k+b*w+b*z],[c*i+c*j+c*k+c*w+c*z]]

Upvotes: 0

Views: 60

Answers (2)

Acsisr
Acsisr

Reputation: 186

The one-liner should look this way:

l3 = [[sum([i*j for j in l2])] for i in l1]

inspectorG4dget will return list of lists of numbers. But then again, his algebra solution will work and is the best one :)

Upvotes: 1

inspectorG4dget
inspectorG4dget

Reputation: 113955

l3 = []
for i in l1:
    temp = 0
    for j in l2:
        temp += i*j
    l3.append([temp])

But of course, there's a one-liner for that:

l3 = [[sum(i*j) for j in l2] for i in l1]

But with some algebra:

total = sum(l2)
l3 = [[i*total] for i in l1]

Upvotes: 3

Related Questions