I have a python list with filenames as follows: [name1, name10, name11, name2, name3, ..., name9].
I want it to be sorted like [name1, name2, name3, ..., name10, name11].
How can I do this?
I know that I can use a special key function (sorted(files, key=lambda name: etc.)), but I am not sure which function to apply.
Thanks for your help!
Try This :
sorted(aList, key= lambda x: (lambda a, _, b: (a, int(b)) if b.isdigit() else (float("inf"), x))(*x.partition(" ")))
This will work as per your requirement. Also it doesn't require any third party library .
Try third party library for natural string sorting called natsort.
>>> import natsort
>>> my_list = [...]
>>> natsort.natsorted(my_list)
You can also specify key for sorting using key argument.
>>> natsort.natsorted(my_list, key=lambda x: ...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With