Skip to main content
 首页 » 编程设计

python之如何查找列表中的任何元素是否存在于字典中

2024年10月01日6del

我有以下代码:

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,如果“photo”或“audio”是 arg 的键之一。

我希望 is_file 返回 False 或其中一种文件类型(如果它在 arg 中设置)。其中一种文件类型可以在 arg 字典中。

此外,我认为这没有优化。我想要一个更好的选择。

请您参考如下方法:

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