0

Say I have images of dogs in a directory with its name and numbering as:

dog 1.jpg
dog 2.jpg
dog 3.jpg
.
.
dog 11.jpg
dog 12.jpg

when I perform sorted(glob.glob('that_dir/*jpg')) and print, it returns:

dog 1.jpg
dog 10.jpg
dog 11.jpg
dog 12.jpg
.
.
dog 8.jpg
dog 9.jpg

is there a way to make it return in order of dog 1.jpg, dog 2.jpg .. dog 12.jpg in this case? or is it wiser to avoid this numbering method altogether and use something like leading zeros instead?

Curerious
  • 31
  • 5
  • Use sorted(glob.glob('that_dir/*jpg'), key = lambda x: int(x[4:].split('.')[0])) – Amit Vikram Singh Apr 01 '21 at 02:05
  • 1
    I think what you're looking for is called a "natural sort" - if you search on that term you should find lots. But adding leading zeros is the quick and easy solution. – Mark Ransom Apr 01 '21 at 02:09
  • Hey, thanks Mark! that's exactly it! I've never heard of that term before, so this is something new for me! – Curerious Apr 01 '21 at 09:18

1 Answers1

1

One way using distutils.version.LooseVersion:

from distutils.version import LooseVersion

l = ['dog 12.jpg', 'dog 1.jpg', 'dog 11.jpg', 
     'dog 2.jpg', 'dog 3.jpg', 'dog 10.jpg']

sorted(l, key=LooseVersion)

Output:

['dog 1.jpg',
 'dog 2.jpg',
 'dog 3.jpg',
 'dog 10.jpg',
 'dog 11.jpg',
 'dog 12.jpg']
Chris
  • 29,127
  • 3
  • 28
  • 51