gpt4 book ai didi

Python - 从列表中的元组中检索元素

转载 作者:行者123 更新时间:2023-12-01 05:51:14 25 4
gpt4 key购买 nike

我是 Python 初学者,正在努力从列表中的元组中检索元素。我想做的是获取水果的值(value)并将其乘以所需的数量。下面的例子将告诉你我的意思。我不知道如何获取元组中的第二个元素。

##Cost of [('apples', 2.0), ('pears', 3.0), ('limes', 4.0)] is 12.25


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

def buyLotsOfFruit(orderList):
## orderList: List of (fruit, numPounds) tuples
## Returns cost of order

totalCost = 0.0
for fruit,price in fruitPrices.items():
if fruit not in fruitPrices:
print 'not here!'
else:
totalCost = totalCost +fruitPrices[fruitPrices.index(fruit)].key() * price
return totalCost

主要是在我的 else 语句中,我无法让它工作。非常感谢所有帮助!

最佳答案

你为什么要循环字典?相反,循环遍历您的列表,并相应地添加到 totalCost

for fruit, n in orderList:
if fruit in fruitPrices:
totalCost += fruitPrices[fruit] * n
else:
print fruit, 'not here!'
<小时/>

您可以简化这一切并执行类似的操作

sum(fruitPrices.get(fruit, 0) * n for fruit, n in orderList)

请注意,如果 fruit 位于 fruitPrices 中,fruitPrices.get(fruit, 0) 将返回 fruitPrices[fruit] code> 和 0 否则。

关于Python - 从列表中的元组中检索元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14250422/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com