【问题标题】:How can I multiply all the numbers from a list to display a new list?如何将列表中的所有数字相乘以显示新列表?
【发布时间】:2014-04-23 22:08:29
【问题描述】:

好的,这真的很重要,我只需要有人帮助我。我对 python 很陌生,所以有很多事情我无法理解。

我正在编写一个程序,要求用户输入食谱名称和它所服务的人数。

然后,它要求用户输入有关成分的信息。我通过创建一个列表来做到这一点,如下所示。

ingredients = []
while True:
 ingredient_name = input("Name your ingredient: ")
 ingredient_quantity: int(input("Write the quantity of your ingredient: "))
 ingredient_unit = input("Write the unit of your ingredient: ")
 ingredients.append((ingredient_name, ingredient_quantity, ingredient_unit))

 cont = input("Continue adding ingredients? [y/n]")
 all_ingredients = " ".join(str(v) for v in ingredients)
 if not cont.lower() in ("y","yes"):
     break

然后程序会显示创建的列表。但是,然后我希望能够要求用户为食谱输入一个新人数,然后将列表的成分数量乘以这个new number,为新人数显示新列表

我完全不知道该怎么做,所以如果有人能解释一下,那对我很有帮助!另外,很抱歉,如果这含糊不清或不清楚,我已尽力以最好的方式解释它。

【问题讨论】:

    标签: python list


    【解决方案1】:

    这就是列表推导的目的。元组解包也非常有用。

    new_ingredients = [(name, quantity*multiplier, unit) for name,quantity,unit in ingredients]
    

    【讨论】:

      猜你喜欢
      • 2022-01-07
      • 1970-01-01
      • 1970-01-01
      • 2014-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-29
      • 2019-07-07
      相关资源
      最近更新 更多