2013-01-10 79 views
1

我是一名Python初学者,正在努力从列表中检索元组。我想要做的是获得一个水果的价值,并乘以所需的数量。下面的例子会告诉你我的意思。我无法弄清楚如何获取元组中的第二个元素。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, 
       '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 

这是主要在我的其他声明,我不能得到它的工作。所有帮助非常感谢!

+0

'buyLotsOfFruit'的缩进是正确的? –

+0

也许,对不起,这是我把它粘贴到这里的时候 –

回答

2

你为什么要遍历字典?相反,在列表中循环,并相应地添加到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]如果fruitfruitPrices0否则。

+0

如果水果不在那里,你不能尝试在这里得到它:'fruitPrices [水果]',所以你不需要放入'continue'或'else' – jackcogdill

+0

我只是写出你的'sum'行。缺少水果的情况下(如果他们可以跳过,无论如何)也可以简洁地处理:'sum(fruitPrices.get(fruit,0)* n for fruit,n in orderList)' – DSM

+0

啊,是的,我将编辑以包含该内容。 – arshajii

0

可以把这下降到一行,但我不认为这会有所帮助。您正在循环价格字典,但应循环遍历orderList,然后查找字典中的水果。

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 
0
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    
      totalCost = totalCost +fruitPrices[fruit] * price 

    return totalCost 
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] 它返回值

相关问题