Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python custom sort list 1/2/3/../9/10

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!

like image 650
beta Avatar asked Dec 02 '25 23:12

beta


2 Answers

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 .

like image 113
coder3521 Avatar answered Dec 04 '25 13:12

coder3521


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: ...)
like image 29
Rahul Gupta Avatar answered Dec 04 '25 15:12

Rahul Gupta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!