Python—从列表的元组中检索元素
我是Python的初学者,正在努力从列表中检索元组中的元素。我想做的是得到一个水果的价值,然后乘以所需的数量。下面的例子将告诉你我的意思。我不知道如何获取元组中的第二个元素Python—从列表的元组中检索元素,python,arrays,list,tuples,Python,Arrays,List,Tuples,我是Python的初学者,正在努力从列表中检索元组中的元素。我想做的是得到一个水果的价值,然后乘以所需的数量。下面的例子将告诉你我的意思。我不知道如何获取元组中的第二个元素 ##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,
##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声明中,我无法让它工作。非常感谢您的帮助 可以把这一点归结为一句话,但我认为这不会有帮助。您正在遍历价格字典,但应该遍历订单列表,然后在字典中查找水果
def buyLotsOfFruit(orderList):
totalCost = 0.0
for fruit, quantity in orderList:
if fruit not in fruitPrices:
print 'not here!'
else:
totalCost = totalCost +fruitPrices[fruit]* quantiy
return totalCost
你为什么翻字典?而是在列表上循环,并相应地添加到
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)
请注意,fruitPrices.get(fruit,0)
将返回fruitPrices[fruit]
如果fruitPrices
中有fruitPrices,则返回0
。注意:
您可以将整个函数放入一行程序中,如下所示:
buyLotsOfFruit = lambda ol: sum(fruitPrices[f] * p for f, p in ol if f in fruitPrices)
或者以另一种方式:
def buyLotsOfFruit(orderList):
## orderList: List of (fruit, numPounds) tuples
## Returns cost of order
totalCost = 0.0
for fruit, pounds in orderList:
if fruit not in fruitPrices:
print 'not here!'
else:
totalCost += fruitPrices[fruit] * pounds
return totalCost
要从字典中检索密钥,您只需执行以下操作:dictionary[key]
它返回值Buylotsofruit
主体的缩进不正确?也许,当我将其粘贴到此处时很抱歉,如果水果不在此处,您无法尝试在此处获取:水果价格[水果]
,所以你不需要输入continue
或else
吗?我刚才正在写你的总和
行。丢失水果的情况(如果可以跳过,无论如何)也可以简单地处理:sum(水果价格。get(水果,0)*n水果,n在订单列表中)
当我逐步了解您的逻辑时,它会更有意义。谢谢你抽出时间!
def buyLotsOfFruit(orderList):
## orderList: List of (fruit, numPounds) tuples
## Returns cost of order
totalCost = 0.0
for fruit, pounds in orderList:
if fruit not in fruitPrices:
print 'not here!'
else:
totalCost += fruitPrices[fruit] * pounds
return totalCost