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
添加回答
举报