3

How can I shorten the following 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

I was thinking in terms of

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

which does not work.

In contrast to this post: Checking file extension, I am also interested in a generalization, which does not focus on the file ending.

Community
  • 1
  • 1
CFW
  • 294
  • 1
  • 5
  • 12

3 Answers3

16

This is a bit shorter

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

It works because endswith() can take a tuple for input as you can see in the docs.

You can even do this to make it case insensitive

images = [x for x in files if x.lower().endswith(('.jpg','.png'))]
Tim
  • 41,901
  • 18
  • 127
  • 145
  • This works great for my MWE, many thanks. As an extension, could endswith() be replaced by something like ''contains()'' and hence be more generally applied to cases that do not focus on the ending? – CFW Dec 21 '16 at 10:20
  • 1
    @CFW python has no contains but it has a `in` keyword. In that case it would be something like `[x for x in files if any(y in x for y in ('.jpg','.png','.JPG'))]` This will also match for example `'abc.pngabc'` – Tim Dec 21 '16 at 10:23
4

How about:

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

but, but, having said that you should really use this answer if you want to check for .endswith. I merely extended your premise (based on your question, which used in).

Recommended reading on list comprehension: python documentation

Graham
  • 7,431
  • 18
  • 59
  • 84
zEro
  • 1,255
  • 14
  • 24
1

Something like this should do it:

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
alexblae
  • 746
  • 1
  • 5
  • 13