The other answers here are good. But anyhow I would like to post mine with some explanations
from os.path import basename,splitext
path_list = ['/home/username/images/s1/4.jpg', '/home/username/images/s1/7.jpg',
'/home/username/images/s1/6.jpg', '/home/username/images/s1/3.jpg',
'/home/username/images/s1/5.jpg', '/home/username/images/s1/10.jpg',
'/home/username/images/s1/9.jpg', '/home/username/images/s1/1.jpg',
'/home/username/images/s1/2.jpg', '/home/username/images/s1/12.jpg',
'/home/username/images/s1/11.jpg', '/home/username/images/s1/8.jpg']
new_list = [splitext(basename(x))[0] for x in path_list]
fin_list = list(zip(path_list,new_list))
fin_list = [x[0] for x in sorted(fin_list,key=lambda x: int(x[1]))]
print(fin_list)
1) Creates a list which has only the file name. 1,2,..
and so on.
new_list = [splitext(basename(x))[0] for x in path_list]
Note: Why [0] ?? Because the output of each splitext(basename(x))[0]
would be like this,
('1','.jpg') , ('4','.jpg')
so [0] 0th
index gives us just the filename!
2) zip each and every item from both iterables with each other and create a list. So this list has values like these,
fin_list = list(zip(path_list,new_list))
#output
('/home/username/images/s1/4.jpg','4.jpg')
3) [x[0] for x in sorted(fin_list,key=lambda x: int(x[1]))]
This one creates a list from the sorted list of fin_list
note key is the main thing here. Key will be the second item from tuple i.e 4,3,7,..
and such. Based on which sorting happens.
finally your output:
['/home/username/images/s1/1.jpg', '/home/username/images/s1/2.jpg',
'/home/username/images/s1/3.jpg', '/home/username/images/s1/4.jpg',
'/home/username/images/s1/5.jpg', '/home/username/images/s1/6.jpg',
'/home/username/images/s1/7.jpg', '/home/username/images/s1/8.jpg',
'/home/username/images/s1/9.jpg', '/home/username/images/s1/10.jpg',
'/home/username/images/s1/11.jpg', '/home/username/images/s1/12.jpg']