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

时间:2013-01-10 03:33:27

标签: 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,   
               '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

主要是在我的声明中,我无法让它发挥作用。非常感谢所有帮助!

4 个答案:

答案 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]位于fruitfruitPrices将会返回0

答案 1 :(得分: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

答案 2 :(得分: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

答案 3 :(得分: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] 它返回值