Question: Through `os.listdir()` I have created a list of hundreds of files picked up from a folder. All the filenames have the following pattern:

```
obj1__5
obj1__10
obj1__15
...
...
obj1__250
...
obj2__5
obj2__10
...
obj2__250
... and so on up to obj99

```

The files in the folder were ordered following this scheme, however when using `os.listdir()` I got a list ordered in this way:

```
obj1__0.png
obj1__10.png
obj1__100.png
obj1__105.png
...
obj1__145.png
obj1__15.png
obj1__150.png
obj1__155.png
...
obj1__190.png
obj1__195.png
obj1__20.png
obj1__200.png
obj1__205.png
... and so on

```

Is there any way to pick up the file in the same order they are displayed in the folder? Or perhaps any sorting function I can use to put them back in their proper order? Thanks

Answer: 
This should work for you.

```
import os
import re

def splitter(name):                                         
    reg = re.search("(\d+)__(\d+)", name)
    return (int(reg.group(1)), int(reg.group(2)))

files = map(lambda x: (x, splitter(x)[0], splitter(x)[1]), os.listdir())

temp = sorted(files, key = lambda x: (x[1], x[2]))   

sortedFiles = map(lambda x: x[0], temp)

```

The `key` argument to the `sorted` function essentially does a multi-argument sort, sorting by the first argument and then sorting on the second argument while respecting the first level of sorting.
You can try that:

```
>>> l = ['obj1__0.png', 'obj1__10.png', 'obj3__15.png', 'obj1__15.png', 'obj2__15.png', 'obj1__100.png']
>>>
>>> sorted(l, key=lambda x: (int(x.split('__')[0][3:]),int(x.split('__')[1].strip('.png'))))
['obj1__0.png', 'obj1__10.png', 'obj1__15.png', 'obj1__100.png', 'obj2__15.png', 'obj3__15.png']

```