我有以下代码:
fileTypes = ["photo", "audio"]
arg = {"photo": "123"}
is_file = True if [True for f in fileTypes if f in arg.keys()] else False
如果“photo”或“audio”是arg
的键之一,则is_file
输出为True
。
我希望 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
关于python - 如何查找列表中的任何元素是否存在于字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42858430/