Python3 快速检查元素是否在元素集合中的方法

Python3 Fast Way To Check If Element In Collection Of Elements

Python3 中,除了使用字典之外,是否有比尝试更快的方法来检查您的元素是否存在于元素集合中?

我对下面的时间进行了计时并尝试 except 与遍历数组相比非常快,有没有更好的方法可以在不使用 try/except 的情况下执行此操作?

import timing

bad_extensions_array = ['.png', '.gif',
                '.map', '.jpg', '.ico', '.gzip', '.idx',
                '.pack', '.eot', '.ttf', '.woff', '.zip',
                '.pfx', '.woff2', '.o', '.node', '.gz',
                '.icns', '.tgz', '.dll', '.js', '.nib',
                '.PNG', '.exe', '.strings', '.xlsx', '.xls',
                '.phar', '.xcf', '.foo', '.bmp', '.ser',
                '.otf', '.gnumeric', '.ods', '.xml', '.graffle',
                '.pdf']

bad_extensions_dict = {
    '.png':True, '.gif':True,
    '.map':True, '.jpg':True, '.ico':True, '.gzip':True, '.idx':True,
    '.pack':True, '.eot':True, '.ttf':True, '.woff':True, '.zip':True,
    '.pfx':True, '.woff2':True, '.o':True, '.node':True, '.gz':True,
    '.icns':True, '.tgz':True, '.dll':True, '.js':True, '.nib':True,
    '.PNG':True, '.exe':True, '.strings':True, '.xlsx':True, '.xls':True,
    '.phar':True, '.xcf':True, '.foo':True, '.bmp':True, '.ser':True,
    '.otf':True, '.gnumeric':True, '.ods':True, '.xml':True, '.graffle':True,
    '.pdf':True
}

ext_ = 'sdsd'

# ext_ not found
# 0:00:00.110999

# ext_ first in array
# 0:00:00.018037

def check_list():
    if ext_ in bad_extensions_array:
        return True
    return False

# ext_ not found
# 0:00:00.043047

# ext_ found
# 0:00:00.018655

def check_dict():
    try:
        return bad_extensions_dict[ext_]
    except:
        return False

for x in range(100000):
    #check_list()
    #check_dict

如@Kevin 所述,in 也适用于字典。它实际上适用于任何标准集合(尽管 str 上的定义略有不同)。

对照字典检查时,您是在确定该键是否存在。

如前所述,如果 bad_extensions 仅代表您不应该使用的扩展,则最好使用一组,例如:

bad_extensions = {
    'bmp', 'dll', 'eot', 'exe', 'foo', 'gif', 'gnumeric', 'graffle', 'gz',
    'gzip', 'icns', 'ico', 'idx', 'jpg', 'js', 'map', 'nib', 'node', 'o',
    'ods', 'otf', 'pack', 'pdf', 'pfx', 'phar', 'png', 'ser', 'strings',
    'tgz', 'ttf', 'woff', 'woff2', 'xcf', 'xls', 'xlsx', 'xml', 'zip'
}