gpt4 book ai didi

python - key 检查时 "key in dict"和 "dict.get(key)"之间的区别

转载 作者:行者123 更新时间:2023-12-01 23:07:23 24 4
gpt4 key购买 nike

当我在做Leetcode 820 ,构建一个 Trie,我的代码中有一个错误。我找到了它,也更正了它,但不明白为什么。谁能帮忙?

我这里做了一个简单的测试代码。程序 1 和程序 2 在做同样的事情,即给定一个单词列表 words,它按照这些单词的逆序构建一个 Trie。变量trie 存储了Trie 树的根,变量leaves 存储了每个单词的起始字符。程序 1 和程序 2 之间的唯一区别在于 # difference 行,我重点关注 2 个程序中 leaves 的不同结果。

words = ["time", "atime", "btime"]

# program 1
trie = dict()
leaves = []
for word in words:
node = trie
for c in reversed(word):
if c not in node: # difference
node[c] = dict()
node = node[c]
leaves.append(node)
print("from program 1: ")
print(leaves)

# program 2
trie = dict()
leaves = []
for word in words:
node = trie
for c in reversed(word):
if not node.get(c): # difference
node[c] = dict()
node = node[c]
leaves.append(node)
print("from program 2: ")
print(leaves)

但是 leaves 的输出完全不同。

from program 1: 
[{'a': {}, 'b': {}}, {}, {}]
from program 2:
[{}, {}, {}]

谁能帮忙解释一下为什么程序1和程序2中leaves的结果不同?提前致谢!

最佳答案

c not in node 仅当 node 不包含键 c 时才为 True。

很多事情可以使 not node.get(c) 返回 True。任何虚假值,例如空的 listdictstr,或者类似 00.0,评估为 bool 值 False,就像 None 一样。因此,任何时候 node 包含 c 但具有虚假值时,您都可能会得到假阴性。

如果您绝对确定您的映射不能包含 None 值,您可以执行以下操作:

if node.get(c) is not None:

当然,显式检查 key 总是比通过其他方式隐式检查要好,因为那样会产生意想不到的副作用。

关于python - key 检查时 "key in dict"和 "dict.get(key)"之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70603241/

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