如何查找列表中是否存在列表的任何元素

时间:2017-03-17 13:09:46

标签: python list python-3.x dictionary optimization

我有以下代码:

fileTypes = ["photo", "audio"]
arg = {"photo": "123"}
is_file = True if [True for f in fileTypes if f in arg.keys()] else False

is_file输出为True,如果"照片"或"音频"是arg的关键之一。

如果在is_file中设置,我希望False返回arg或其中一种文件类型。其中一种文件类型可以在arg dict中。

另外,我认为这不是优化的。我想要一个更好的选择。

1 个答案:

答案 0 :(得分:2)

any()怎么样?

from timeit import timeit

def list_comprehension_method():

    fileTypes = ["photo", "audio"]
    arg = {"photo": "123"}
    return True if [True for f in fileTypes if f in arg.keys()] else False

def any_method():

    fileTypes = ["photo", "audio"]
    arg = {"photo": "123"}
    return any(f in arg.keys() for f in fileTypes)


number = 1000

print('any_method:                 ', timeit('f()', 'from __main__ import any_method as f', number=number))
print('list_comprehension_method:  ', timeit('f()', 'from __main__ import list_comprehension_method as f', number=number))

Python 2.7:

any_method:                 0.001070976257324218
list_comprehension_method:  0.001577138900756836

Python 3.6:

any_method:                  0.0013788840005872771
list_comprehension_method:   0.0015097739960765466