如何将列表中的所有数字与另一个列表中的其他数字相乘。 (同一订单)

问题描述 投票:0回答:2

我想分别求和2列表的倍数(a [0]和b [0]直到a [n]和b [n​​]注意:l使用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中没有更多))

python sum multiplying dot-product
2个回答
4
投票

使用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))


A functional approach is pretty pythonic (assuming fillvalue is still 0):
from operator import mul

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

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

1
投票

如果总是发生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
© www.soinside.com 2019 - 2024. All rights reserved.