[英]Python loop through list of tuples
我有以下 function:
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,它將計算總價。 對於列出的項目,否則如果缺少一個將返回無
注意:磅是與 orderlist 中的每個水果相關聯的元組列表中的 integer。
根據您的邏輯,認為您的代碼必須是這樣的。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.