gpt4 book ai didi

python - 为什么 a = a ['k' ] = {} 创建一个无限嵌套的字典?

转载 作者:太空狗 更新时间:2023-10-29 21:06:21 26 4
gpt4 key购买 nike

这是我创建无限嵌套字典的 Python 代码:

a = a['k'] = {}

print(a)
print(a['k'])
print(a['k']['k'])
print(a is a['k'])

这是输出:

{'k': {...}}
{'k': {...}}
{'k': {...}}
True

输出显示 a['k'] 引用 a 本身,这使得它无限嵌套。

我猜测声明:

a = a['k'] = {}

表现得像:

new = {}
a = new
a['k'] = new

这确实会创建一个无限嵌套的字典。

我看了Section 7.2: Assignment statements Python 语言引用 但我找不到任何暗示 a = a['k'] = {} 应该首先设置 a 到新字典然后在那个字典中插入一个键/值对。以下是我认为相关但未回答我的问题的引用资料的一些摘录:

If the target list is a single target with no trailing comma, optionally in parentheses, the object is assigned to that target.

If the target is a subscription: The primary expression in the reference is evaluated. It should yield either a mutable sequence object (such as a list) or a mapping object (such as a dictionary). Next, the subscript expression is evaluated.

If the primary is a mapping object (such as a dictionary), the subscript must have a type compatible with the mapping’s key type, and the mapping is then asked to create a key/datum pair which maps the subscript to the assigned object. This can either replace an existing key/value pair with the same key value, or insert a new key/value pair (if no key with the same value existed).

这些摘录中的每一个都定义了具有单个目标的赋值行为,例如 a = {}a['k'] = {} 但它们不' 似乎在谈论在 a = a['k'] = {} 的情况下应该发生什么。此类声明的评估顺序记录在哪里?


这个问题现在已经解决了。 GPhilo的回答指向Section 7.2: Assignment statements的相关条款.相关条款在开头是正确的,但我之前忽略了它。在这里:

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.

现在让我们将它与语法进行比较。

赋值语句定义为

assignment_stmt ::=  (target_list "=")+ (starred_expression | yield_expression)

所以声明

a = a['k'] = {}

有两个 target_list 元素,即 aa['k'],以及一个 starred_expression元素,即 {},因此 {} 被分配给每个目标列表 aa['k'] 从左到右。

最佳答案

根据 the section 7.2 you quoted,赋值语句中的赋值是从左到右解析的(强调我的):

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.

这意味着是的,您的陈述确实等同于:

new = {}
a = new
a['k'] = new

作为快速反证,交换赋值顺序会导致错误:

a['k'] = a = {}

加注

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

关于python - 为什么 a = a ['k' ] = {} 创建一个无限嵌套的字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54808430/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com