如何将一个列表中的所有数字与另一个列表中的另一个数字相乘求和。 (相同顺序)

How to sum the multiply all numbers in a list with another numbers in another list. (Same order)

我想分别求和2个列表的乘积(a[0]与b[0]直到a[n]与b[n])注意:我使用n因为a和b的列表是免费的输入,所以,可以有很多。

如果输入的数据是:

A = [ 12 , 0 , 3 , 7 , 2]
B = [ 1 , 2 , 5 , 4]

我要A*B的和(12*1 + 0*2 + 3*5 + 7*4 + 2*0 (因为B里没有了))

itertools.zip_longestfillvalue 参数一起使用:

sum(x*y for x, y in zip_longest(A, B, fillvalue=0))

代码:

from itertools import zip_longest

A = [12, 0, 3, 7, 2]
B = [1, 2, 5, 4]

print(sum(x*y for x, y in zip_longest(A, B, fillvalue=0)))
# 55

由于 fillvalue 为 0 并且不会导致操作发生任何变化 (2 * 0 = 0),您也可以只使用 zip

sum(x*y for x, y in zip(A, B))


函数式方法 非常pythonic(假设fillvalue仍然是0):

from operator import mul

A = [12, 0, 3, 7, 2]
B = [1, 2, 5, 4]

print(sum(map(mul, A, B)))
# 55

如果总是这样len(A) >= len(B)

>>> sum([A[i]*B[i] for i in range(len(B))])
55

否则修改为

sum([A[i]*B[i] for i in range(min([len(A), len(B)]))])

更新

我刚刚注意到 zip 也适用于不同的列表长度, 所以我认为最好的是:

>>> sum([a*b for a, b in zip(A, B)])
55