【问题标题】:Python loop through list of tuplesPython循环遍历元组列表
【发布时间】:2020-08-22 19:31:36
【问题描述】:

我有以下功能:

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 中的每个水果相关联的元组列表中的整数。

【问题讨论】:

  • 您的意思是:'if fruit[0] not in fruitPrices:'?
  • 是的,如果任何水果未列在水果价格中,它将不返回任何其他方式,它将从水果价格中获取价格并乘以该水果的磅数
  • 你的代码肯定因为磅而有错误吗?您应该将其包含在您的问题中。

标签: python list loops tuples


【解决方案1】:

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

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

【讨论】:

  • 这样做只会返回第一项的总价。在我们的示例中,苹果 2*2 = 4。它不会继续循环遍历其他项目。
  • 这样做我猜你会得到orderList中提到的水果的总价。
  • @Abdullah 它实际上会遍历所有内容。仔细检查你的结果。它返回 2 个苹果、3 个梨和 4 个酸橙的总价格。
  • 它现在工作了,我在里面有回报,否则忘了拿出来
猜你喜欢
  • 1970-01-01
  • 2018-10-26
  • 2019-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-15
  • 2017-11-06
  • 1970-01-01
相关资源
最近更新 更多