(令人惊讶)python dict"has_key"比“输入"更快 [英] (surprisingly) python dict "has_key" faster than "in"

查看:105
本文介绍了(令人惊讶)python dict"has_key"比“输入"更快的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从流行的信息以及在net + stackoverflow上搜索,似乎在Python字典中查找关键字时,"in"比"has_key"要快.但是,我最近的经历恰恰相反,我不知道为什么会这样吗?考虑以下形式的代码:

From popular information and also searching on the net+stackoverflow, it seems that "in" is faster than "has_key" for key lookups in python dictionary. However, my recent experience has been quite the opposite and I have no clue why so? Consider the code of the following form:

for f in F:
    if 'A' in f:
        AList.append(f)
        #if f in FDICT.keys():
        if FDICT.has_key(f):
            idx_AList.append(FDICT[f])
    elif 'B' in f:
        BList.append(f)
        #if f in FDICT.keys():
        if FDICT.has_key(f):
            idx_BList.append(FDICT[f])

在上面的方法中,切换到"has_key"可以使代码快5万倍,即使在很小的文件上也是如此.这真是令人莫名其妙-有人知道发生了什么吗?

In the above, switching to "has_key" makes the code 50000x times faster even on very small files. This is quite baffling -- does anyone know what's going on?

推荐答案

它是f in FDICT,而不是f in FDICT.keys().使用keys可以构建所有键的列表,并逐一遍历,而使用f in FDICT则可以使用基于哈希的高效查找.

It's f in FDICT, not f in FDICT.keys(). Using keys builds a list of all the keys and goes through it one by one, whereas using f in FDICT uses an efficient hash-based lookup.

这篇关于(令人惊讶)python dict"has_key"比“输入"更快的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆