dict.has_key(x)与'x in dict' [英] dict.has_key(x) versus 'x in dict'
问题描述
您好,
我一直在使用has_key()方法来测试字典
是否包含某个键。最近我尝试使用''in'',例如
d = {...}
如果k在d:
...
并且发现当要进行大量的关键测试时,它似乎表现得更好。
。我还注意到has_key()计划从未来(C)Python版本中删除
。
是否采用''in''测试方式有一个优化的实现比较
到has_key()?这是因为has_key()被淘汰了吗?
谢谢,
Paul
Paul Melis写道:
我一直在使用has_key()方法来测试字典是否
包含某个键。最近我尝试使用''in'',例如
d = {...}
如果k在d:
...
并且发现当要进行大量的关键测试时,它似乎表现得更好。
。我还注意到has_key()计划从未来(C)Python版本中删除
。
是否采用''in''测试方式有一个优化的实现比较
到has_key()?
否,但是完整的方法调用比引擎盖下的C级别的调用要慢得多。在"运营商。
这就是为什么例如
string [:len(prefix)] ==前缀
通常要快得多
string.startswith(前缀)
以及为什么
如果字符串中有字符:
string = string.replace(字符,替换)
快于
string = string.replace(字符,替换)
如果角色大多数时间都没有,尽管事实上替换
如果找不到角色,
方法实际上并没有做什么。
< / F>
Paul Melis写道:
我一直在使用has_key()方法测试是否
字典包含某个键。最近我尝试使用
''''',例如
d = {...}
如果k in d:
...
如果k在d.keys()中,则不会是确切的替代品?
问候,
Bj?
-
BOFH借口#17:
行中的脂肪电子
Bjoern Schliessmann写道:
如果k在d.keys()中,则不会是是确切的替代?
no。这将O(1)操作转换为O(n)操作,这将是相当愚蠢的。
< / F>
Hello,
I''ve always been using the has_key() method to test if a dictionary
contains a certain key. Recently I tried the same using ''in'', e.g.
d = { ... }
if k in d:
...
and found that it seems to perform a lot better when lots of key-tests
are to be performed. I also noticed that has_key() is scheduled to be
removed from future (C)Python versions.
Does the ''in'' way of testing have an optimized implementation compared
to has_key()? Is that the reason has_key() is being phased out?
Thanks,
Paul
Paul Melis wrote:
I''ve always been using the has_key() method to test if a dictionary
contains a certain key. Recently I tried the same using ''in'', e.g.
d = { ... }
if k in d:
...
and found that it seems to perform a lot better when lots of key-tests
are to be performed. I also noticed that has_key() is scheduled to be
removed from future (C)Python versions.
Does the ''in'' way of testing have an optimized implementation compared
to has_key()?no, but full method calls are a lot slower than the under-the-hood C-level
call used by the "in" operator.
this is why e.g.
string[:len(prefix)] == prefix
is often a lot faster than
string.startswith(prefix)
and why
if character in string:
string = string.replace(character, replacement)
is faster than
string = string.replace(character, replacement)
if the character isn''t there most of the time, despite the fact that the "replace"
method doesn''t actually do something if the character isn''t found.
</F>
Paul Melis wrote:
I''ve always been using the has_key() method to test if a
dictionary contains a certain key. Recently I tried the same using
''in'', e.g.
d = { ... }
if k in d:
...Wouldn''t be "if k in d.keys()" be the exact replacement?
Regards,
Bj?rn
--
BOFH excuse #17:
fat electrons in the lines
Bjoern Schliessmann wrote:
Wouldn''t be "if k in d.keys()" be the exact replacement?no. that would convert an O(1) operation to an O(n) operation, which
would be rather silly.
</F>
这篇关于dict.has_key(x)与'x in dict'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!