Python赋值运算符优先级 - (a, b) = a[b] = {}, 5 [英] Python Assignment Operator Precedence - (a, b) = a[b] = {}, 5
问题描述
我在 Twitter 上看到了这个 Python 片段,并且对输出感到非常困惑:
<预><代码>>>>a, b = a[b] = {}, 5>>>一种{5: ({...}, 5)}这里发生了什么?
来自 赋值语句文档:
<块引用>赋值语句评估表达式列表(记住这可以是单个表达式或逗号分隔的列表,后者产生一个元组)并将单个结果对象从左到右分配给每个目标列表.
您有两个分配目标列表;a, b
和 a[b]
,值 {}, 5
从左到右分配给这两个目标.>
首先将 {}, 5
元组解包为 a, b
.您现在有 a = {}
和 b = 5
.请注意,{}
是可变的.
接下来将相同的字典和整数分配给 a[b]
,其中 a
的计算结果为字典,b
的计算结果为 5
,因此您将字典中的键 5
设置为元组 ({}, 5)
以创建循环引用.{...}
因此引用了 a
已经引用的同一个对象.
因为分配是从左到右进行的,您可以将其分解为:
a, b = {}, 5a[b] = a, b
so a[b][0]
与 a
是同一个对象:
I saw this Python snippet on Twitter and was quite confused by the output:
>>> a, b = a[b] = {}, 5
>>> a
{5: ({...}, 5)}
What is going on here?
From the Assignment statements documentation:
An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.
You have two assignment target lists; a, b
, and a[b]
, the value {}, 5
is assigned to those two targets from left to right.
First the {}, 5
tuple is unpacked to a, b
. You now have a = {}
and b = 5
. Note that {}
is mutable.
Next you assign the same dictionary and integer to a[b]
, where a
evaluates to the dictionary, and b
evaluates to 5
, so you are setting the key 5
in the dictionary to the tuple ({}, 5)
creating a circular reference. The {...}
thus refers to the same object that a
is already referencing.
Because assignment takes place from left to right, you can break this down to:
a, b = {}, 5
a[b] = a, b
so a[b][0]
is the same object as a
:
>>> a, b = {}, 5
>>> a[b] = a, b
>>> a
{5: ({...}, 5)}
>>> a[b][0] is a
True
这篇关于Python赋值运算符优先级 - (a, b) = a[b] = {}, 5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!