Python循环遍历元组列表



我有以下功能:

def buyLotsOfFruit(orderlist):
totalCost = 0.0
for fruit in orderlist:
if fruit not in fruitPrices:
return None
else:
totalCost = totalCost+fruitPrices.get(fruit)*pound
return totalCost

其中:

fruitPrices = {'apples': 2.00, 'oranges': 1.50, 'pears': 1.75,
'limes': 0.75, 'strawberries': 1.00}

假设我有以下订单清单:

orderlist = [('apples', 2), ('pears', 3), ('limes', 4)]

当我想让它在fruitPrices列表中查看并检查是否所有项目都存在时,循环不断返回none,它将计算总价。对于列出的项目,否则如果缺少一个,将不返回

注意:该磅是与订单列表中的每个水果相关联的元组列表中的整数。

根据您的逻辑,您的代码必须是这样的。

def buyLotsOfFruit(orderlist):
totalCost = 0.0
for fruit, pound in orderlist:
if fruit not in fruitPrices:
return None
else:
totalCost = totalCost+fruitPrices.get(fruit, 0)*pound
return totalCost

最新更新