gpt4 book ai didi

Python 字典 : "in" vs "get"

转载 作者:行者123 更新时间:2023-12-04 22:56:03 27 4
gpt4 key购买 nike

在字典中搜索元素时,我对“in”和“get”的使用有点困惑。

根据这个时间复杂度表,here :当使用“in”时,我们得到 O(n) 与“get”我们得到 O(1)。

在下面这两个代码片段中,他们实现了同样的事情,但显然使用 get 会快得多?

#Recall that for "get" the second parameter is returned if key is not found

#O(1) time complexity
if dict.get(key, False):
return "found item"

#O(n) time complexity
if key in dict:
return "found item"

我不明白当它们都可以实现相同的事情时,使用 get 会如何改变时间复杂度。除了 get 调用实际上会返回该值(如果找到)。

问题:当它们都达到相同的结果时,“in”时间复杂度是 O(n) 而“get”的时间复杂度仅为 O(1) 是怎么回事?如果这是真的,是否有理由在字典中使用“in”?

最佳答案

get()如果键存在于字典中,则返回给定键的值。
in根据键是否存在于字典中,返回一个 bool 值。

使用 get()如果你需要值(value)。使用 in如果您只需要测试 key 是否存在。

关于Python 字典 : "in" vs "get",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46509361/

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