Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

fixing the way how to sort element in a list using python sorted method

I have this list containing the following images with these the name structure "number.image"

  • The list stores the elements of a local folder based on a path.
[1.image, 2.image, 3.image, 4.image, 5.image, 6.image, 7.image, 8.image, 9.image, 10.image, 11.image, 12.image, 13.image]

applying the python build-in sorted() method to make sure the elements in the list are sorted in proper manner I got this result. As you see the order is not correct.

1.image 
10.image
11.image
12.image
13.image
2.image
3.image
4.image
5.image
6.image
7.image
8.image
9.image

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you want to use the inbuilt sorted function and not install a third-party library such as natsort, you can use a lambda for the key argument that interprets the stem of the file as an integer:

>>> filenames = [
...     '1.image',
...     '10.image',
...     '11.image',
...     '12.image',
...     '13.image',
...     '2.image',
...     '3.image',
...     '4.image',
...     '5.image',
...     '6.image',
...     '7.image',
...     '8.image',
...     '9.image',
... ]
>>> sorted_filenames = sorted(filenames, key=lambda f: int(f.split('.')[0]))
>>> print('\n'.join(sorted_filenames))
1.image
2.image
3.image
4.image
5.image
6.image
7.image
8.image
9.image
10.image
11.image
12.image
13.image
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading