如何缩短以下MWE?
files = ['a.txt', 'b.jpg', 'c.png', 'd.JPG', 'e.JPG']
images = [x for x in files if '.jpg' in x or '.png' in x or '.JPG' in x]
print images
我在思考
files = ['a.txt', 'b.jpg', 'c.png', 'd.JPG', 'e.JPG']
images = [x for x in files if ('.jpg' or '.png' or '.JPG') in x]
print images
哪个不起作用。
与这篇文章相比:Checking file extension,我也对一般性化感兴趣,而这种概括并不关注文件的结尾。
答案 0 :(得分:15)
这有点短
files = ['a.txt', 'b.jpg', 'c.png', 'd.JPG', 'e.JPG']
images = [x for x in files if x.endswith(('.jpg','.png','.JPG'))]
print images
它的工作原理是因为endswith()
可以使用元组输入,因为您可以看到in the docs。
您甚至可以将其设为不区分大小写
images = [x for x in files if x.lower().endswith(('.jpg','.png'))]
答案 1 :(得分:4)
怎么样:
files = ['a.txt', 'b.jpg', 'c.png', 'd.JPG', 'e.JPG']
formats = ('.jpg', '.png', '.JPG')
# this gets you the images
images = [file for file in files if any (format in file for format in formats))
# The above is equivalent to the following statement which is longer
# and looks complicated but probably easy to understand for someone new to [python list comprehension][1]
images = [file for file in files if any (format for format in formats if format in file))
但是,但是,如果你想检查.endswith
,你应该真的使用this answer。我只是扩展了你的前提(基于你的问题,使用了in
)。
关于列表理解的推荐阅读:python documentation
答案 2 :(得分:1)
这样的事情应该这样做:
import os
files = ['a.txt', 'b.jpg', 'c.png', 'd.JPG', 'e.JPG']
images = [x for x in files if os.path.splitext(x)[-1] in ['.jpg','.png','.JPG']]
print images