- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我不确定我是否在这里遗漏了一些微不足道的东西,但我终其一生都无法弄清楚下面的代码如何设法提供它所提供的输出。
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/
我有这个简单的代码: #!/usr/bin/perl @inp = map 2**$_, 0..6; @cc = grep { my $num = $inp[$_]; my $sum
这是我发现的一个微妙之处 keys() . $ perl -e 'use warnings; use strict; my $d = { "ab" => 1 }; my @e = keys(%{$d-
我不确定我是否在这里遗漏了一些微不足道的东西,但我终其一生都无法弄清楚下面的代码如何设法提供它所提供的输出。 import collections tree = collections.default
在寻找使用嵌套字典的方法时,我发现了 nosklo 发布的以下代码,我想解释一下。 class AutoVivification(dict): """Implementation of per
假设我想在 Python 中进行类似 PERL 的自动激活,即: >>> d = Autovivifier() >>> d = ['nested']['key']['value']=10 >>> d
我是一名优秀的程序员,十分优秀!