如何缩短多个IF .... IN ... OR语句?

CFW*_*CFW 3 python if-statement list python-2.7

如何缩短以下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
Run Code Online (Sandbox Code Playgroud)

我在思考

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
Run Code Online (Sandbox Code Playgroud)

这不起作用.

与这篇文章相反:检查文件扩展名,我也对一个概括感兴趣,它不关注文件结尾.

Tim*_*Tim 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
Run Code Online (Sandbox Code Playgroud)

它的工作原理是因为endswith()你可以在文档中看到输入的元组.

你甚至可以这样做,使它不区分大小写

images = [x for x in files if x.lower().endswith(('.jpg','.png'))]
Run Code Online (Sandbox Code Playgroud)