Multiplying two sets of numbers in python

最后都变了- 提交于 2020-02-07 04:41:51

问题


I have two lists of numbers, say [1, 2, 3, 4, 5] and [7, 8, 9, 10, 11], and I would like to form a new list which consists of the products of each member in the first list with each member in the second list. In this case, there would be 5*5 = 25 elements in the new list.

I have been unable to do this so far with a while() loop. This is what I have so far:

x = 0
y = 99
results = []
while x < 5:
    x = x + 1
    results.append(x*y)
while y < 11:
    y = y + 1
    results.append(x*y)

回答1:


Wht dont you try with known old ways;

list1 = range(1, 100)
list2 = range(10, 50, 5)

new_values = []

for x in list1:
    for y in list2:
        new_values.append(x*y)



回答2:


Use itertools.product to generate all possible 2-tuples, then calculate the product of that:

[x * y for (x, y) in itertools.product([1,2,3,4,5], [7,8,9,10,11])]



回答3:


The problem is an example of an outer product. The answer already posted with itertools.product is the way I would do this as well.

But here's an alternative with numpy, which is usually more efficient than working in pure python for crunching numeric data.

>>> import numpy as np
>>> x1 = np.array([1,2,3,4,5])
>>> x2 = np.array([7,8,9,10,11])
>>> np.outer(x1,x2)
array([[ 7,  8,  9, 10, 11],
       [14, 16, 18, 20, 22],
       [21, 24, 27, 30, 33],
       [28, 32, 36, 40, 44],
       [35, 40, 45, 50, 55]])
>>> np.ravel(np.outer(x1,x2))
array([ 7,  8,  9, 10, 11, 14, 16, 18, 20, 22, 21, 24, 27, 30, 33, 28, 32,
       36, 40, 44, 35, 40, 45, 50, 55])



回答4:


Without any importing, you can do:

[x * y for x in range(1, 6) for y in range(7, 12)]

or alternatively:

[[x * y for x in range(1, 6)] for y in range(7, 12)]

To split out the different multiples, but it depends which order you want the results in.




回答5:


from functools import partial

mult = lambda x, y: x * y

l1 = [2,3,4,5,5]
l2 = [5,3,23,4,4]

results = []

for n in l1:
    results.extend( map( partial(mult, n) , l2) )

print results


来源:https://stackoverflow.com/questions/20352776/multiplying-two-sets-of-numbers-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!