4
votes

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?

2
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
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
Also, I don't know what you mean by "without slicing the file name". What do you think split() does? - roganjosh

2 Answers

8
votes

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.

2
votes

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)