如何在Python中执行两个列表的元素相乘?

我想要执行元素明智的乘法,在Python中将两个列表乘以值,就像我们可以在Matlab中一样。

这是我将如何在Matlab中做到这一点。

a = [1,2,3,4] b = [2,3,4,5] a .* b = [2, 6, 12, 20] 

列表理解将给出16个列表条目,对于来自b ayx每个组合x * y 。 不确定如何映射这个。

如果有人感兴趣为什么,我有一个数据集,并希望乘以Numpy.linspace(1.0, 0.5, num=len(dataset)) =)

使用与zip()混合的列表理解:。

 [a*b for a,b in zip(lista,listb)] 

由于您已经在使用numpy ,所以将数据存储在一个numpy数组而不是列表中是很有意义的。 一旦你做到这一点,你可以免费获得元素明智的产品:

 In [1]: import numpy as np In [2]: a = np.array([1,2,3,4]) In [3]: b = np.array([2,3,4,5]) In [4]: a * b Out[4]: array([ 2, 6, 12, 20]) 

使用np.multiply(a,b):

 import numpy as np a = [1,2,3,4] b = [2,3,4,5] np.multiply(a,b) 

你可以尝试在循环中乘以每个元素。 做这个的简短手段是

 ab = [a[i]*b[i] for i in range(len(a))] 

相当直观的做法是:

 a = [1,2,3,4] b = [2,3,4,5] ab = [] #Create empty list for i in range(0, len(a)): ab.append(a[i]*b[i]) #Adds each element to the list 

还有一个答案:

-1 …需要导入
+1 …非常可读

 import operator a = [1,2,3,4] b = [10,11,12,13] list(map(operator.mul, a, b)) 

输出[10,22,36,52]

对于大型列表,我们可以这样做:

 product_iter_object = itertools.imap(operator.mul, [1,2,3,4], [2,3,4,5]) 

product_iter_object.next()给出输出列表中的每个元素。

输出将是两个input列表中较短的一个的长度。

创build一个数组; 将每个列表乘以数组; 将数组转换为列表

 import numpy as np a = [1,2,3,4] b = [2,3,4,5] c = (np.ones(len(a))*a*b).tolist() [2.0, 6.0, 12.0, 20.0] 

你可以用lambda乘法

 foo=[1,2,3,4] bar=[1,2,5,55] l=map(lambda x,y:x*y,foo,bar) 

gahooa的答案是正确的,如标题中所表述的问题,但如果列表已经是numpy格式大于十,它会快得多(3个数量级),以及更可读,做简单的numpy乘法NPE。 我得到这些时机:

 0.0049ms -> N = 4, a = [i for i in range(N)], c = [a*b for a,b in zip(a, b)] 0.0075ms -> N = 4, a = [i for i in range(N)], c = a * b 0.0167ms -> N = 4, a = np.arange(N), c = [a*b for a,b in zip(a, b)] 0.0013ms -> N = 4, a = np.arange(N), c = a * b 0.0171ms -> N = 40, a = [i for i in range(N)], c = [a*b for a,b in zip(a, b)] 0.0095ms -> N = 40, a = [i for i in range(N)], c = a * b 0.1077ms -> N = 40, a = np.arange(N), c = [a*b for a,b in zip(a, b)] 0.0013ms -> N = 40, a = np.arange(N), c = a * b 0.1485ms -> N = 400, a = [i for i in range(N)], c = [a*b for a,b in zip(a, b)] 0.0397ms -> N = 400, a = [i for i in range(N)], c = a * b 1.0348ms -> N = 400, a = np.arange(N), c = [a*b for a,b in zip(a, b)] 0.0020ms -> N = 400, a = np.arange(N), c = a * b 

即从下面的testing程序。

 import timeit init = [''' import numpy as np N = {} a = {} b = np.linspace(0.0, 0.5, len(a)) '''.format(i, j) for i in [4, 40, 400] for j in ['[i for i in range(N)]', 'np.arange(N)']] func = ['''c = [a*b for a,b in zip(a, b)]''', '''c = a * b'''] for i in init: for f in func: lines = i.split('\n') print('{:6.4f}ms -> {}, {}, {}'.format( timeit.timeit(f, setup=i, number=1000), lines[2], lines[3], f)) 

可以使用枚举。

 [val*b[i] for i, val in enumerate(a)] 
Interesting Posts