Python循环遍历元组列表

Abd*_*lah -2 python loops tuples list

我有以下功能:

def buyLotsOfFruit(orderlist):
    totalCost = 0.0
    for fruit in orderlist:
        if fruit not in fruitPrices:
            return None
        else:
            totalCost = totalCost+fruitPrices.get(fruit)*pound
            return totalCost
Run Code Online (Sandbox Code Playgroud)

在哪里:

fruitPrices = {'apples': 2.00, 'oranges': 1.50, 'pears': 1.75,
           'limes': 0.75, 'strawberries': 1.00}
Run Code Online (Sandbox Code Playgroud)

假设我有以下订单:

orderlist = [('apples', 2), ('pears', 3), ('limes', 4)]
Run Code Online (Sandbox Code Playgroud)

当我希望它在 FruitPrices 列表中查看并检查所有项目是否存在时,循环不断返回 none 它将计算总价格。对于列出的项目,否则如果缺少一个将返回 none

注意:磅是与订单列表中每个水果相关联的元组列表中的整数。

小智 5

认为您的代码必须是这样的,这取决于您的逻辑。

def buyLotsOfFruit(orderlist):
    totalCost = 0.0
    for fruit, pound in orderlist:
        if fruit not in fruitPrices:
            return None
        else:
            totalCost = totalCost+fruitPrices.get(fruit, 0)*pound
    return totalCost
Run Code Online (Sandbox Code Playgroud)