Reputation: 3
How do I multiply every element of one list with every element of another list in Python and then sum the result of the multiplying results variations?
list_1 = [0, 1, 2, 3, 4, 5]
list_2 = [11, 23, m]
Where m element in the list_2 can be any number while the length of the elements in the list is entered with the input. So basically that list contains minimum of 2 elements and can go to up to 12 based on the user requirements.
What I am looking for is a function/algorithm which will allow the following list of the results.:
0*11 + 0*23 +..+ 0*m
1*11 + 0*23 +..+ 0*m
2*11 + 0*23 +..+ 0*m
..
3*11 + 2*23 + .. + 5*m
..
5*11 + 5*23 +..+ 5*m
Upvotes: 0
Views: 663
Reputation: 282026
itertools.product
can help you generate all ways to select elements of list1
to multiply by elements of list2
.
sums = []
for list1_choices in itertools.product(list1, repeat=len(list2)):
sums.append(sum(x*y for x, y in zip(list1_choices, list2))
Or, as a list comprehension:
[sum(x*y for x, y in zip(list1_choices, list2))
for list1_choices in itertools.product(list1, repeat=len(list2))]
Upvotes: 2
Reputation: 27812
You can use a for loop:
for x in list_1:
print sum(x * y for y in list_2)
Upvotes: 0