5

I have a list of strings with my filenames:

flist = ['0.png','10.png', '3.png', '4.png', '100.png']
flist.sort()
print(flist)

Output:

['0.png', '10.png', '100.png', '3.png', '4.png']

But I want:

['0.png', '3.png', '4.png', '10.png', '100.png']

Is there a simple way to do this?

Artur Müller Romanov
  • 4,417
  • 10
  • 73
  • 132
  • 4
    Possible duplicate of [Does Python have a built in function for string natural sort?](https://stackoverflow.com/questions/4836710/does-python-have-a-built-in-function-for-string-natural-sort) – roganjosh Oct 10 '18 at 10:02
  • Thank you for the hint but I think the solutions on this Thread are not simple enough. I know that I can start slicing around my filenames to achieve the goal but I was wondering if there is a SIMPLE way, such as bruno desthuilliers provided. Thanks anyway – Artur Müller Romanov Oct 10 '18 at 10:11
  • Yes, but you should note that the answer given is entirely dependent on being able to use `split()` to isolate the numerical value. The duplicate works in a whole range of cases. The title of your question (should other people stumble across this in searches) belies the specific case you have. – roganjosh Oct 10 '18 at 10:12
  • Also, I don't know what you mean by "without slicing the file name". What do you think `split()` _does_? – roganjosh Oct 10 '18 at 10:14

2 Answers2

9

Yes:

flist.sort(key=lambda fname: int(fname.split('.')[0]))

Explanation: strings are lexically sorted so "10" comes before "3" (because "1" < "3", so whatever comes after "1" in the first string is ignored). So we use list.sort()'s key argument which is a callback function that takes a list item and return the value to be used for ordering for this item - in your case, an integer built from the first part of the filename. This way the list is properly sorted on the numerical values.

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
3

You can also do that like this:

flist = ['0.png','10.png', '3.png', '4.png', '100.png']
flist.sort(key=lambda x: '{0:0>8}'.format(x))
print(flist)
ArunPratap
  • 4,816
  • 7
  • 25
  • 43