Python - 检查多个条件中的任何一个是否为真
Python - Checking whether any of multiple conditions are true
我正在尝试就地修改列表以删除文件扩展名不匹配的条目。我通过编写多个 'or' 条件
来完成这项工作
from os import listdir
image_extensions = ['jpg','.png']
files = listdir('/home')
files = [x for x in files if '.jpg' in x or '.png' in x]
print files
我想让它使用 image_extensions 变量,以便我可以轻松添加更多条件。我最近尝试的失败是 "requires string as left operand, not list":
from os import listdir
image_extensions = ['jpg','.png']
files = listdir('/home')
files = [x for x in files if any(s for s in image_extensions in x)]
print files
应该这样做:
files = [x for x in files if any(s in x for s in image_extensions)]
# |<-->|
检查文件名中是否包含任何扩展名x
另一种解决方案:
>>> filter(lambda f: filter(f.endswith, image_extensions), files)
与之前的答案相比,对该表达式进行时间分析表明,与之前的答案相比有一些改进:
>>> import timeit
>>>
>>> timeit.timeit("import os;l = os.listdir('.');ext = ['txt', 'ini', 'cfg'];filter(lambda f: filter(f.endswith, ext), l)", number=10000)
0.6541688442230225
>>>
>>>
>>> timeit.timeit("import os;l = os.listdir('.');ext = ['txt', 'ini', 'cfg'];files=[x for x in l if any(s in x for s in ext)]", number=10000)
0.64410400390625
>>>
我正在尝试就地修改列表以删除文件扩展名不匹配的条目。我通过编写多个 'or' 条件
来完成这项工作from os import listdir
image_extensions = ['jpg','.png']
files = listdir('/home')
files = [x for x in files if '.jpg' in x or '.png' in x]
print files
我想让它使用 image_extensions 变量,以便我可以轻松添加更多条件。我最近尝试的失败是 "requires string as left operand, not list":
from os import listdir
image_extensions = ['jpg','.png']
files = listdir('/home')
files = [x for x in files if any(s for s in image_extensions in x)]
print files
应该这样做:
files = [x for x in files if any(s in x for s in image_extensions)]
# |<-->|
检查文件名中是否包含任何扩展名x
另一种解决方案:
>>> filter(lambda f: filter(f.endswith, image_extensions), files)
与之前的答案相比,对该表达式进行时间分析表明,与之前的答案相比有一些改进:
>>> import timeit
>>>
>>> timeit.timeit("import os;l = os.listdir('.');ext = ['txt', 'ini', 'cfg'];filter(lambda f: filter(f.endswith, ext), l)", number=10000)
0.6541688442230225
>>>
>>>
>>> timeit.timeit("import os;l = os.listdir('.');ext = ['txt', 'ini', 'cfg'];files=[x for x in l if any(s in x for s in ext)]", number=10000)
0.64410400390625
>>>