1

我试图弄清楚这个程序将打印什么,但我对函数实际打印的内容有疑问

def main():
d = {1 : "car",
     2 : "house",
     3 : "boat",
     4 : "dog",
     5 : "kitchen"} 

L = list(d.keys()) #i know that here a list L is created with values [1,2,3,4,5]
i = 0 
while i < len(L):# while i is less than 5 because of length of list L
    k = L[i]     # k = l[0] so k == 1
    if k < 3 :   # if 1 < 3
     d[ d[k] ] = "zebra" d[ d[1] ] = #zebra so it adds zebra to the dictionary key 1    #right?

    i += 1      # here just i += 1 simple enough and while loop continues
                # loop continues and adds zebra to dictionary key 2 and stops
 for k in d :   
    print(k, d[k]) #This is were im having trouble understanding how everything is printed

main()
4

2 回答 2

1
d = {
    1 : "car",
    2 : "house",
    3 : "boat",
    4 : "dog",
    5 : "kitchen"
} 

for key, value in d.items():
    print (key, value)

for key in d.keys():
    print (key, d[key])

for key in d:
    print (key, d[key])

最后两个循环是等价的。

我想知道为什么要打印最后两行

第一次通过循环:

k=1

所以 d[k] 等价于

d[1]

所以

d[ d[k] ] 

相当于

d[ d[1] ]

d[1] is "car"

所以这给了你

d[ 'car' ]

并且代码这样做:

d[ 'car' ] = 'zebra'
于 2013-08-11T16:41:11.287 回答
0

您可以使用 迭代字典的键for elem in testDict,代码只是这样做并获取每个键的值并打印它。如果您对顺序感到困惑,请注意字典没有顺序,因此键和值不会以任何顺序打印。

就像是 :

>>> testDict = {'a':1, 'b':2, 'c':3}
>>> for elem in testDict:
print('Key: {}, Value: {}'.format(elem, testDict[elem]))


Key: a, Value: 1
Key: c, Value: 3
Key: b, Value: 2

更新- 代码打印'car', 'zebra'等,因为当 for 循环遇到小于 3 的键值时,它是1, 2用于您的字典,然后d[1]d[2]yield "car"and "house",然后将其初始化为键值"zebra"使用d['car'] = 'zebra'and d['house'] = 'zebra',因此结果。

于 2013-08-11T16:35:34.737 回答