[英]Need help understanding dictionaries in python
I'm new to coding and wrote a script.我是编码新手并编写了脚本。 I can't understand why the total being displayed is wrong and changes each time I run the program.
我不明白为什么显示的总数是错误的,并且每次运行程序时都会发生变化。 I know that dictionaries do not store the key and value in the same order each time but I don't understand why the totals are wrong and never the same?
我知道字典不会每次都以相同的顺序存储键和值,但我不明白为什么总数是错误的并且永远不会相同? Can someone help?
有人可以帮忙吗? I'm looking for an explanation so I can learn from my mistake.
我正在寻找一个解释,这样我就可以从我的错误中吸取教训。
stock = [["mp40", 4], ["crowbar", 3], ["machete", 4], ["5_person_tent", 3],
["gps", 10], ["duffle_bag", 3], ["first_aid_kit", 2], ["horse", 1],
["military_mre", 7], ["camping_stove", 1], ["hunting_vest", 2],
["jogging_pants", 3], ["timberlands", 2], ["gas_generator", 3],
["gasoline", 500], ["gas_can", 100], ["pontiac_grand_dam", 1]]
prices = [["mp40", 390], ["crowbar", 20], ["machete",40],["5_person_tent",250],
["gps", 97], ["duffle_bag",20], ["first_aid_kit",15], ["horse", 3000],
["military_mre",15],["camping_stove",15], ["hunting_vest", 60],
["jogging_pants", 60], ["timberlands", 150], ["gas_generator",180],
["gasoline", 3],["gas_can", 20], ["pontiac_grand_dam", 2000]]
def buy():
purchase =input("What item you want to buy?\n")
total = 0
for item in stock:
if purchase in stock.keys():
if stock[item] > 0:
amount =int(input("How many would you like to purchase?\n"))
total += (prices[item]*(amount))
stock[item] -=(amount)
print ('You owe'+' '+'$'+str(total))
input('press enter to continue \n')
return total
if stock[item]<1:
print ("we don't have any left\n")
if purchase!=item:
print ("We do not sell that.\n")
a=0
while a==0:
buy()
You need to make stock
and prices
dictionaries, not lists.您需要制作
stock
和prices
词典,而不是列表。 Fortunately, your current data makes this easy, as dict
can take a list of key-value pairs as an argument.幸运的是,您当前的数据使这变得容易,因为
dict
可以将键值对列表作为参数。 That is,那是,
stock = [...] # current definition
stock = dict(stock)
prices = [ ... ] # current definition
prices = dict(prices)
Defining the dictionary "manually" would look something like “手动”定义字典看起来像
stock = {"mp40":4,
"crowbar":3,
"machete":4, } # etc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.