gpt4 book ai didi

python - 你能用 Python defaultdict 和 autovivification 解释这种行为吗

转载 作者:太空宇宙 更新时间:2023-11-03 15:07:09 32 4
gpt4 key购买 nike

我不确定我是否在这里遗漏了一些微不足道的东西,但我终其一生都无法弄清楚下面的代码如何设法提供它所提供的输出。

import collections

tree = collections.defaultdict(dict)
tree[0][1] = tree[1]
print tree
tree[1][2] = tree[2]
print tree

这是神奇的输出:

defaultdict(<type 'dict'>, {0: {1: {}}, 1: {}})
defaultdict(<type 'dict'>, {0: {1: {2: {}}}, 1: {2: {}}, 2: {}})

第一行输出完全有意义。然后考虑赋值 tree[1][2] = tree[2] 及其后续输出。

我知道条目 2:{} 是通过计算 RHS 表达式 tree[2] 创建的。

我还了解条目 1: {2: {}} 是通过评估 LHS 表达式 tree[1][2] 并将其分配给RHS 的值。

我不明白的是字典条目 0: {1: {}} 是如何更新为 0: {1: {2: {}}} 当没有引用 tree[0] 时。

最佳答案

因为当你做 tree[0][1] = tree[1] , tree[0][1]引用与 tree[1] 相同的对象, 因此如果 tree[1] 内部发生任何变化, 它也会反射(reflect)在 tree[0][1] 中.

而且,当你做 tree[1][2] ,您实际上是在 tree[1] 内部进行更改, 而不是制作 tree[1]引用一个新对象。

例如,在您进行更改后尝试这样做 -

>>> tree[1]['blah'] = 'Hello'
>>> print(tree)
defaultdict(<class 'dict'>, {0: {1: {2: {}, 'blah': 'Hello'}}, 1: {2: {}, 'blah': 'Hello'}, 2: {}})

仅当您执行类似 - tree[1] = <somethingelse> 的操作时, 你正在制作 tree[1]引用一个新对象,在这种情况下它不会反射(reflect)在 tree[0][1] 中.

关于python - 你能用 Python defaultdict 和 autovivification 解释这种行为吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31367397/

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