猿问

您能解释一下吗,代码课程中的一堂课

我当时在代码学院学习代码,当时我在其中编写代码,但没有得到练习的解决方案,我单击了给我解决方案选项,然后得到了我不理解该程序的解决方案。


prices = {"banana": 4,"apple": 2,"orange": 1.5,"pear": 3}


stock = {"banana": 6, "apple": 0, "orange": 32, "pear": 15}


for food in prices:

  print food

  print "price: %s" % prices[food]

  print "stock: %s" % stock[food]

然后打印出来


orange

price: 1.5

stock: 32

pear

price: 3

stock: 15

banana

price: 4

stock: 6

apple

price: 2

stock: 0

你能解释一下它的过程吗?它如何打印上面给出的输出


慕村9548890
浏览 145回答 2
2回答

米脂

知道这个问题会有所帮助。但是我可以尝试在不知道问题的情况下从高层次上解释该程序。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。

红糖糍粑

您有两个字典prices,分别是和stockprices = {"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 dictstock = {"banana": 6, "apple": 0, "orange": 32, "pear": 15} #stock dictfor 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
随时随地看视频慕课网APP

相关分类

Python
我要回答