繁体   English   中英

Python 循环遍历元组列表

[英]Python loop through list of tuples

我有以下 function:

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)]

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

注意:磅是与 orderlist 中的每个水果相关联的元组列表中的 integer。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM