0

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

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • Is this what you were looking for? http://stackoverflow.com/questions/10271484/python-dot-multiply-two-lists [a*b for a,b in zip(lista,listb)] – samsquanch Jul 22 '13 at 21:45

3 Answers3

4
[sum(x * y for x in list_2) for y in list_1]
richsilv
  • 7,993
  • 1
  • 23
  • 29
  • 1
    It's better without the inside brackets: ``[sum(x * y for x in list_2) for y in list_1]``: sum works on generators. – hivert Jul 22 '13 at 21:52
  • 1
    That's not actually what the OP asked for. Take another look at his desired output; he described his requirements oddly. – user2357112 Jul 22 '13 at 21:57
  • Also, if this was the desired behavior, `sum_1 = sum(list_1); return [sum_1*y for y in list_2]` would be `O(len(list_1) + len(list_2))` instead of `O(len(list_1)*len(list_2))`. – user2357112 Jul 22 '13 at 22:08
  • Yes, I see what you mean, this isn't actually what he's asking for. – richsilv Jul 22 '13 at 22:30
2

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))]
user2357112
  • 260,549
  • 28
  • 431
  • 505
  • This is indeed the solution to the question which has been (rather confusingly) posed - the OP needs a sumproduct across all possible selections from `list_1` of the same length as `list_2`, with replacement. – richsilv Jul 22 '13 at 22:34
0

You can use a for loop:

for x in list_1:
    print sum(x * y for y in list_2)
jh314
  • 27,144
  • 16
  • 62
  • 82