0

如以下两个代码片段所示,链式赋值的顺序很重要(即node = node[ch] = {}不等同于node[ch] = node = {}.

trie = {}
node = trie
for ch in "word":
    if ch in node:
        node = node[ch]
    else:
        node = node[ch] = {} # chained assignment #1
print(trie) # {}
trie = {}
node = trie
for ch in "word":
    if ch in node:
        node = node[ch]
    else:
        node[ch] = node = {} # chained assignment #2
print(trie) # {'w': {'o': {'r': {'d': {}}}}}

为什么顺序很重要?


根据另一个 SO question,链式分配

a = b = c

相当于:

tmp = c
a = c
b = c

我验证了等效形式产生了相同的行为。IE

        # node = node[ch] = {} # chained assignment #1
        tmp = {}
        node = tmp
        node[ch] = tmp

导致一个print(trie){}

同时

        node[ch] = node = {} # chained assignment #2
        tmp = {}
        node[ch] = tmp
        node = tmp

导致一个print(trie){'w': {'o': {'r': {'d': {}}}}}

4

1 回答 1

4

你基本上在最后回答了你的问题。

node = tmp
node[ch] = tmp

node[ch] = tmp
node = tmp

不等价。一旦你这样做node = tmp,你就会丢失以前的内容node,并用新的字典替换它们。这意味着在第一种情况下,您会立即失去对trie循环内部的引用,并且不能再对其进行变异。在第二种情况下,您更改旧结果,然后重新分配node给新字典。

于 2021-06-02T21:54:27.693 回答