Gianluca John Massimiani Gianluca John Massimiani - 1 month ago 8
Python Question

Python: sorting strings by only one of their "part"

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

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']