Python循环遍历元组列表

2024-09-27 21:23:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下功能:

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

其中:

fruitPrices = {'apples': 2.00, 'oranges': 1.50, 'pears': 1.75,
           'limes': 0.75, 'strawberries': 1.00}

假设我有以下订单列表:

orderlist = [('apples', 2), ('pears', 3), ('limes', 4)]

循环不断返回无时,我希望它在水果价格清单,并检查是否所有的项目存在,它将计算总价格。对于列出的项目,如果缺少一个,则将不返回任何项目

注意:pound是与orderlist中每个水果相关联的元组列表中的整数


Tags: 项目in功能列表return价格fruitpound
1条回答
网友
1楼 · 发布于 2024-09-27 21:23:17

根据您的逻辑,您的代码必须是这样的

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

相关问题 更多 >

    热门问题