【问题标题】:Subtracting an integer from nested list从嵌套列表中减去一个整数
【发布时间】:2020-12-21 14:13:06
【问题描述】:

• 如果有足够的糖果出售,系统必须从数量 [项目 2] 中减去输入的金额,以便显示商店中剩余的糖果数量) • 如果没有足够的糖果出售(客户想要购买的糖果多于可用的糖果),系统必须通知用户无法进行交易。需要在 def 函数中完成,任何人都可以帮助解决这个问题!

lst_s = [
["Smarties", 5, 37], ["Cookie", 8, 80], ["Fizzies", 4, 50], ["Chocolate bar", 4, 25]
]

def update_quantity():
    name = str(input("Enter name of confectionary: "))
    price = str(input("Enter price: "))
    amount = int(input("enter quantity customer wants to buy"))

    for i in range(len(lst_s)):
        item = lst_s[i]
        iamount = item[2]
        if amount > iamount:
            print("Sorry not enough in store to sell")
        else:
            iamount = iamount - amount
            print(lst_s)

如果我输入名称为 Cookie,价格为 8,数量为 3,则所需的输出将是:

["Smarties", 5, 37], ["Cookie", 8, 77], ["Fizzies", 4, 50], ["Chocolate bar", 4, 25]

因为原来的 Cookie 数量已经减去了 3 个

【问题讨论】:

    标签: python list nested-lists calculation python-3.9


    【解决方案1】:

    试试这个:

    def update_quantity():
      name = str(input("Enter name of confectionary: "))
      price = str(input("Enter price: "))
      amount = int(input("enter quantity customer wants to buy"))
    
      for i in range(len(lst_s)):
        item = lst_s[i]
        item_name = item[0]
        iamount = item[2]
        if name != item_name:
            continue
        if amount > iamount:
            print("Sorry not enough in store to sell")
        else:
            lst_s[i][2] = iamount - amount
            print(lst_s)
    

    【讨论】:

      【解决方案2】:

      应该相对简单。您可能想使用 dict 来存储产品。

      lst_s = [
        ["Smarties", 5, 37],
        ["Cookie", 8, 80],
        ["Fizzies", 4, 50],
        ["Chocolate bar", 4, 25],
      ]
      
      def update_quantity():
          name = str(input("Enter name of confectionary: "))
          price = str(input("Enter price: "))
          amount = int(input("enter quantity customer wants to buy"))
      
          for product in lst_s:
              if product[0] == name:
                  if amount > product[2] :
                      print("Sorry not enough in store to sell")
                  else:
                      product[2] = product[2] - amount
                  break;
          print(lst_s)
          
      update_quantity();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多