I would like to sort a list which includes a set such as;
100.avi
10000.avi
10002.avi
1003.avi ....
I need to do some process using the files in numeric order. If I use sorted
it does not care about the values, it sorts on the first character, second character, and so on - string sorting.
I tried to use [:-4] but I tried to do this on the list not the element of the list. Because it is late when I have the element. Is there any way?
Thanks in advance
You can use a custom sorting function to extract the number from each element of the list and use it as the comparison key. You'd need to convert it to int
to ensure it compares like number:
>>> lst = ['100.avi', '10000.avi', '10002.avi', '1003.avi']
>>> sorted(lst, key=lambda x: int(x.split('.', 1)[0]))
['100.avi', '1003.avi', '10000.avi', '10002.avi']
由于给定列表的所有字符串都以.avi
扩展名结尾,因此可以使用切片功能。
sorted(lst, key=lambda x: int(x[:-4]))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.