2013-01-10 109 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] 它返回值

相關問題