简体   繁体   English

这个python嵌套循环的工作方式是什么?

[英]How does this python nested for loops work?

Can anyone explain why the output of the following nested loop is {1:6, 2:6, 3:6} ? 谁能解释为什么以下嵌套循环的输出为{1:6, 2:6, 3:6}

>>> {x:y for x in [1, 2, 3] for y in [4, 5, 6]}
{1:6, 2:6, 3:6}
my_dict = {x:y for x in [1,2,3] for y in [4,5,6]}

is the same is creating it as follows 是相同的创建它如下

my_dict = {}
for x in [1,2,3]:
    for y in [4,5,6]:
        my_dict[x] = y

Which would look like this if you unroll the loops: 如果展开循环,将如下所示:

my_dict = {}
my_dict[1] = 4
my_dict[1] = 5
my_dict[1] = 6
my_dict[2] = 4
my_dict[2] = 5
my_dict[2] = 6
my_dict[3] = 4
my_dict[3] = 5
my_dict[3] = 6

You are effectively inserting nine key value pairs into the dictionary. 您实际上是在字典中插入九个键值对。 However, each time you insert a pair with a key that already exists it overwrites the previous value. 但是,每次插入具有已存在密钥的密钥对时,都会覆盖先前的值。 Thus you only ended up with the last insert for each key where the value was six. 因此,对于每个键,最后只插入最后一个值为6的键。

The difference is you are making a dictionary vs a list. 不同之处在于您要制作字典还是列表。 In your own example, you are effectively constructing a dictionary and because you set a different value for the same key 3 times, the last value sticks. 在您自己的示例中,您正在有效地构造字典,并且由于您为相同的键设置了3次不同的值,因此最后一个值仍然有效。

You are effectively doing: 您正在有效地做:

dict[1] = 4
dict[1] = 5
dict[1] = 6
...
dict[3] = 4
dict[3] = 5
dict[3] = 6

So the last value sticks. 因此,最后一个价值仍然存在。

如果期望创建{1:4, 2:5, 3:6} ,请尝试以下操作:

{x[0]:x[1] for x in zip([1,2,3], [4,5,6])}  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM