在我的代码中有两个单独的列表。我想将 list[0] 的值乘以 list2[0],将 list[1] 的值乘以 list2[1] 等等。
value = []
quantity = []
for line in fh:
if line.startswith("Value"):
line = line[18:len(line)]
line = float(line)
value.append(line)
for line2 in fh:
if line2.startswith("Amount"):
line2 = line2[17:len(line2)]
line2 = float(line2)
quantity.append(line2)
首先,我的“数量”列表出现“列表索引超出范围”的情况。这是为什么?
然后相乘这样的东西行得通吗?
total = 0.0
temp = 0.0
for i in range(len(value))
temp = value[i]*quantity[i]
total = total + temp
请您参考如下方法:
使用带有 1 的 fillvalue 的 itertools.izip_longest,如果列表的长度不同,您会将最长列表的元素乘以 1。
from itertools import izip_longest
l1 = [1,2,3,4]
l2 = [1,2,3,4,5]
print([x*y for x,y in (izip_longest(l1,l2,fillvalue=1))])
[1, 4, 9, 16, 5]
