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

3
如何缩短以下的最小工作示例(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

无法工作。

与此帖子相反:检查文件扩展名,我还对一般化感兴趣,这不仅关注于文件结尾。

3个回答

16

这篇文章比较短

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()可以接受一个元组作为输入,您可以在文档中看到。

您甚至可以这样做,使其不区分大小写。

images = [x for x in files if x.lower().endswith(('.jpg','.png'))]

这对我的MWE非常有效,非常感谢。作为扩展,是否可以用类似于“contains()”的东西替换endswith(),从而更普遍地应用于不仅仅是关注结尾的情况? - CFW
1
@CFW Python没有contains函数,但是有一个in关键字。在这种情况下,可以使用类似于[x for x in files if any(y in x for y in ('.jpg','.png','.JPG'))]的语句。这也会匹配例如'abc.pngabc'这样的字符串。 - Tim

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))

但是,如果您想检查以什么结尾,真正应该使用这个答案。我只是在您的前提下进行了扩展(基于您的问题,使用了in)。
列表推导式的推荐阅读:Python文档

为什么不使用any(format in file for format in formats) - tobias_k
当然,这是等价的 @tobias_k。 - zEro
1
@zEro:最好只保留编辑过的答案并删除之前提到的那个。此外,您可以从答案中删除tobias_k的名字,他不会介意的 ;) - Moinuddin Quadri
我保留了原始内容,这样原帖作者可以对比并理解我们在那里做了什么。 - zEro
1
在这种情况下,最好翻转答案。重点应该放在高效实现结果上。因为 Stack Overflow 不仅是针对 OP 的,其他人也会在将来参考它 :) - Moinuddin Quadri
没错,@ MoinuddinQuadri。正在更新。 - zEro

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接