如以下两个代码片段所示,链式赋值的顺序很重要(即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': {}}}}}