Home > Mobile >  Multiply two lists but multiply each number in the first list by all numbers in the second list in p
Multiply two lists but multiply each number in the first list by all numbers in the second list in p

Time:11-30

I have two lists I want to multiply each number in the first list by all numbers in the second list

[1,2]x[1,2,3]

I want my result to be like this [(1x1) (1x2) (1x3),(2x1) (2x2) (2x3)]

CodePudding user response:

numpy

a = np.array([1,2])
b = np.array([1,2,3])

c = (a[:,None]*b).sum(1)

output: array([ 6, 12])

python

a = [1,2]
b = [1,2,3]

c = [sum(x*y for y in b) for x in a]

output: [6, 12]


old answer (product per element)

numpy
a = np.array([1,2])
b = np.array([1,2,3])
c = (a[:,None]*b).ravel()

output: array([1, 2, 3, 2, 4, 6])

python
a = [1,2]
b = [1,2,3]

c = [x*y for x in a for y in b]

## OR
from itertools import product
c = [x*y for x,y in product(a,b)]

output: [1, 2, 3, 2, 4, 6]

CodePudding user response:

def multiplyLists(list1: list, list2:list) -> list:
    toReturn = []
    for i in list1:
        temp_sum = 0
        for j in list2:
            temp_sum  = i * j
        toReturn.append(temp_sum)
    return toReturn

CodePudding user response:

Another way using numpy (that you can extend to many other functions between two lists):

a = [1,2]
b = [1,2,3]
np.multiply.outer(a,b).ravel()
#array([1, 2, 3, 2, 4, 6])

CodePudding user response:

As the comments point out a pure Python solution will be very different to a numpy solution.

Pyhton

Here it woud be straightforward to use a nested loop or list comprehension:

list1 = [1, 2]
list2 = [1, 2, 3]

lst_output = []
for i in list1:
    for j in list2:
        lst_output .append(i*j)

#equivalent alternative
lst_output = [i*j for i in list1 for j in list2]

Numpy

There are mny ways to go about it with numpy as well. Here's one example:

arr1 = np.array([1, 2])
arr2 = np.array([1, 2, 3])

xx, yy = np.meshgrid(arr1, arr2)

arr_output = xx * yy 

# optionally (to get a 1d array)
arr_output_flat = arr_output.flatten() 

Edit: Reading your question again I noticed you state you actually want the output to be 2 sums (of 3 products). I suggest you phrase more precisely what you want an what you've tried. But to provide that here's what you can do with the lists or arrays from above:

# Pure Python
lst_output = [sum(i*j for j in list2) for i in list1]

# Numpy
xx, yy = np.meshgrid(arr1, arr2)
arr_output = np.sum(xx * yy, axis=0)
  • Related