簡體   English   中英

需要幫助理解python中的字典

[英]Need help understanding dictionaries in python

我是編碼新手並編寫了腳本。 我不明白為什么顯示的總數是錯誤的,並且每次運行程序時都會發生變化。 我知道字典不會每次都以相同的順序存儲鍵和值,但我不明白為什么總數是錯誤的並且永遠不會相同? 有人可以幫忙嗎? 我正在尋找一個解釋,這樣我就可以從我的錯誤中吸取教訓。

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

您需要制作stockprices詞典,而不是列表。 幸運的是,您當前的數據使這變得容易,因為dict可以將鍵值對列表作為參數。 那是,

stock = [...]   # current definition
stock = dict(stock)

prices = [ ... ] # current definition
prices = dict(prices)

“手動”定義字典看起來像

stock = {"mp40":4,
         "crowbar":3,
         "machete":4, } # etc

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM