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