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.
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]))
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
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