Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort alphanumeric list in python

I have a list as

a = [["1", "ok", "na"], ["15", "asd", "asdasd"], ["100", "uhu", "plo"], ["10", "iju", "tlo"], ["ISC_1", "des", "det"], ["12", "asd", "assrg"], ["ARF", "asd", "rf"]]

I want this list to be sorted as below:

[['1', 'ok', 'na'], ['10', 'iju', 'tlo'], ['12', 'asd', 'assrg'], ['15', 'asd', 'asdasd'], ['100', 'uhu', 'plo'], ['ARF', 'asd', 'rf'], ['ISC_1', 'des', 'det']]

I have used a.sort()

It is resulting as below:

[['1', 'ok', 'na'], ['10', 'iju', 'tlo'], ['100', 'uhu', 'plo'], ['12', 'asd', 'assrg'], ['15', 'asd', 'asdasd'], ['ARF', 'asd', 'rf'], ['ISC_1', 'des', 'det']]

Please help me how to sort in this case.

like image 686
Shanky Avatar asked Apr 21 '26 23:04

Shanky


2 Answers

You can use the key named argument.
It accepts a function that returns the value the sorting function should compare items by.

sorted(a, key = lambda l: int(l[0]))
like image 77
Neo Avatar answered Apr 24 '26 13:04

Neo


To be ready for non numeric values you can use

a.sort(key = lambda l: int(l[0]) if l[0].isnumeric() else 99999)
# or
b=sorted(a,key = lambda l: int(l[0]) if l[0].isnumeric() else 99999)

to see non-numeric last or

a.sort(key = lambda l: int(l[0]) if l[0].isnumeric() else 0)
# or
b=sorted(a,key = lambda l: int(l[0]) if l[0].isnumeric() else 0)

to see them first

like image 20
Leonhard Triendl Avatar answered Apr 24 '26 11:04

Leonhard Triendl



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!