2 回答

TA貢獻1836條經驗 獲得超3個贊
知道這個問題會有所幫助。但是我可以嘗試在不知道問題的情況下從高層次上解釋該程序。
prices = {"banana": 4,"apple": 2,"orange": 1.5,"pear": 3}
stock = {"banana": 6, "apple": 0, "orange": 32, "pear": 15}
這是兩個字典的定義,第一個字典僅存儲每個水果的價格,第二個字典存儲存儲中的水果數量(庫存)。
for food in prices: ### For loop iterates over the Keys of the dict (fruitnames)
print food ## printing current key for iteration
print "price: %s" % prices[food] ## printing price of the fruit
print "stock: %s" % stock[food] ## printing stock of the fruit.
順便說一下,這看起來像Python2語法,因為該print語句沒有括號。我強烈建議改為學習python3。

TA貢獻1815條經驗 獲得超6個贊
您有兩個字典prices,分別是和stock
prices = {"banana": 4,"apple": 2,"orange": 1.5,"pear": 3}
stock = {"banana": 6, "apple": 0, "orange": 32, "pear": 15}
你遍歷keys的prices通過字典for food in prices:此行。
閱讀此代碼的注釋:
prices = {"banana": 4,"apple": 2,"orange": 1.5,"pear": 3} #prices dict
stock = {"banana": 6, "apple": 0, "orange": 32, "pear": 15} #stock dict
for food in prices: #iterate over the keys of prices dict
print food #print the key
print "price: %s" % prices[food] #print the value of prices dict at food key
print "stock: %s" % stock[food] #print the value of stock dict at food key
添加回答
舉報