pythonlistsortingsortedlist

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"

[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

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:

    >>> from pathlib import Path
    >>> 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(Path(f).stem))
    >>> # Arguably less readable alternative using list indexing  splitting on the period manually: 
    >>> # 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