从嵌套列表中减去一个整数

问题描述

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

lst_s = [
["Smarties",5,37],["Cookie",8,80],["Fizzies",4,50],["Chocolate bar",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",77],25]

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

解决方法

试试这个:

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

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

lst_s = [
  ["Smarties",5,37],["Cookie",8,80],["Fizzies",4,50],["Chocolate bar",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();