gpt4 book ai didi

Python - 字典未正确更新

转载 作者:太空宇宙 更新时间:2023-11-03 17:50:13 25 4
gpt4 key购买 nike

我正在尝试运行这个超市程序。但是,项目列表未正确更新。

stock = {
"banana": 6,"apple": 0,"orange": 32,"pear": 15
}
prices = {
"banana": 4,"apple": 2,"orange": 1.5,"pear": 3
}

def compute_bill(food):
total = 0
for item in food:
if stock[item] > 0:
total += prices[item]
stock[item] -= 1
return total

print "\n"
print " Welcome to Supermarket!"
print "List of grocery items :"
print("{:<5}{:<8}{:<9}{:<10}".format("Num","Item"," Cost"," In Stock"))
counter = 0
for x,y in enumerate(prices.items()):
print("{:<5}{:<10}RS {:.2f}{:>5}".format(x+1,y[0],y[1],stock.values()[counter]))
counter += 1

print "Specify the number of items : "
number = int (raw_input ())
order = {}
for i in range(number):
groceryitem = raw_input("Please enter the name of product %s:" % (i+1))
itemNo = int(raw_input("How many iteam %s ?" % groceryitem))
order[groceryitem] = itemNo

total = compute_bill(order)
print "total",total

counter = 0
for x,y in enumerate(prices.items()):
print("{:<5}{:<10}RS {:.2f}{:>5}".format(x+1,y[0],y[1],stock.values()[counter]))
counter += 1

这低于我的输入和我得到的输出

                Welcome to Supermarket!
List of grocery items :
Num Item Cost In Stock
1 orange RS 1.50 32
2 pear RS 3.00 15
3 banana RS 4.00 6
4 apple RS 2.00 0
Specify the number of items :
2
Please enter the name of product 1:banana
How many iteam banana ?4
Please enter the name of product 2:pear
How many iteam pear ?5

Num Item Cost In Stock
1 orange RS 1.50 32
2 pear RS 3.00 14
3 banana RS 4.00 5
4 apple RS 2.00 0

既然我指定了 4 个香蕉和 5 个梨,那么这些商品的数量应该从库存 list 中减去。为什么股票词典中的值没有更新。

请帮忙!

最佳答案

它们正在更新,但只减少了 1,因为您写入了 stock[item] -= 1。如果您想根据购买的商品数量减少库存,则需要将其更改为 stock[item] -= food[item]。您可能还需要执行total += food[item]*prices[item],以便“购物者”根据购买的商品数量正确收费。

关于Python - 字典未正确更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29200688/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com