Python赋值运算符优先级 - (a, b) = a[b] = {}, 5 [英] Python Assignment Operator Precedence - (a, b) = a[b] = {}, 5

查看:65
本文介绍了Python赋值运算符优先级 - (a, b) = a[b] = {}, 5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Twitter 上看到了这个 Python 片段,并且对输出感到非常困惑:

<预><代码>>>>a, b = a[b] = {}, 5>>>一种{5: ({...}, 5)}

这里发生了什么?

解决方案

来自 赋值语句文档:

<块引用>

赋值语句评估表达式列表(记住这可以是单个表达式或逗号分隔的列表,后者产生一个元组)并将单个结果对象从左到右分配给每个目标列表.

您有两个分配目标列表;a, ba[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 是同一个对象:

<预><代码>>>>a, b = {}, 5>>>a[b] = a, b>>>一种{5: ({...}, 5)}>>>a[b][0] 是一个真的

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆