【问题标题】:Python3 Fast Way To Check If Element In Collection Of ElementsPython3快速检查元素集合中的元素的方法
【发布时间】:2016-03-03 18:12:12
【问题描述】:

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

我对以下时间进行了计时并尝试了,但与循环遍历数组相比非常快,有没有更好的方法可以在不使用 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

【问题讨论】:

  • in 也适用于字典。但是,如果您只关心键而不关心值,请考虑使用集合。
  • 如果密钥不存在,您可以使用 .get(ext_,False) 返回 False,但我不确定它是否更快
  • 不,dict.get 一直较慢,但 indict 上的效果和在 set 上一样好(两者都比 list 快得多)

标签: python python-3.x big-o


【解决方案1】:

正如@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'
}

【讨论】:

  • 哇,使用 in 和 set 比尝试除了 dict 快 60 倍
  • @ClickThisNick 我注意到您的集合中还有一些值,它们仅因大小写而异。考虑将bad_extensions 中的每一项都设为小写并与extension.lower() in bad_extensions 核对。
  • 测试了这个案例,.lower 使它几乎慢了两倍,我在这种情况下交易速度以获得准确性。我也不需要检查扩展中的.。这也将使它有点更快
  • @ClickThisNick 我已重新格式化 bad_extensions 以进行排序并省略句点。
  • 这真是太棒了。只是想知道,集合的顺序重要吗?
猜你喜欢
  • 1970-01-01
  • 2015-11-05
  • 1970-01-01
  • 2017-12-11
  • 2016-01-14
  • 2016-06-18
  • 2023-02-04
  • 2015-02-12
  • 2011-10-20
相关资源
最近更新 更多