0

I know this is a very basic question but from the answers I saw while searching I didn't find something good enough for this one.

I have the following names of files I received while using mylist = os.listdir(<folder_path>):

['file.0', 'file.1', 'file.10', 'file.100', 'file.2', 'file.3']  

I want sort this list in an ascending order like that:

['file.0', 'file.1', 'file.2', 'file.3', 'file.10', 'file.100']  

I tried to use mylist.sort() but it it leaves the list without any changes. The sorted() function also doesn't do any change.

One workaround is to separate the numbers from the strings and cast them to integers to a new array:

[0, 1, 10, 100, 2, 3]  

And then sort them:

[0, 1, 2, 3, 10, 100]  

Then I need a function to do "file." + i.

But is there a better way to do it ?

I noticed that Windows does it and I think they are doing it with some sting sorting:
enter image description here

E235
  • 11,560
  • 24
  • 91
  • 141
  • 1
    It should be pointed out that it _is_ actually sorting it, however since they are strings `file.10` comes before `file.2` because `1` is less then `2` (the `0` is irrelevant). – Aaron N. Brock May 23 '18 at 16:49

1 Answers1

1

I would recommend using split('.'), which splits your elements of your list where it finds .. If you then cast the last element to int, you can use that as a key to sort on:

sorted(mylist, key = lambda x: int(x.split('.')[-1]))

Returns:

['file.0', 'file.1', 'file.2', 'file.3', 'file.10', 'file.100']
sacuL
  • 49,704
  • 8
  • 81
  • 106