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

标签 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

如果“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/

相关文章:

python - pip 在自定义目录中安装依赖项

python - 如何将时间序列数据转换为图像?

python - 在 PyObjc 和 Cocoa 中实现 NSText 委托(delegate)方法

Python 类和集合

java - 子列表抛出的 ConcurrentModificationException

Python; urllib 错误 : AttributeError: 'bytes' object has no attribute 'read'

python - 将 print() 的输出发送到 tkinter Text 小部件

ruby-on-rails - Rails - 通过连接表以逗号分隔的列表

python - 更改字典列表中的相同值

python - 在 Python 列表中查找 "x"最大差异