gpt4 book ai didi

python - 在 Python 中比较字典键查找的性能如何?

转载 作者:太空狗 更新时间:2023-10-29 22:04:28 24 4
gpt4 key购买 nike

如何:

dict = {}
if key not in dict:
dict[key] = foo

比较:

try:
dict[key]
except KeyError:
dict[key] = foo

也就是说,查找一个键是否比通过 dict.keys() 进行线性搜索更快,我假设第一种形式就可以?

最佳答案

只是澄清一点:if key not in d 不会对 d 的键进行线性搜索。它使用字典的哈希表来快速找到键。

关于python - 在 Python 中比较字典键查找的性能如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3679286/

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