Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python sort list of lists based on inner element AND ignore case

let's say I have the following list in python

[ [1,"C"], [2, "D"], [3,"a"], [4,"b"] ]

I would like to sort the list by the letters so it would be

[ [3,"a"], [4,"b"], [1,"C"], [2, "D"] ]

To sort by the inner character, I would do sorted(unsortedlist, key=itemgetter(1)).
To sort by ignoring case, I would do sorted(unsortedlist, key=str.lower).

How do I sort by an inner element AND ignoring case at the same time?

like image 963
quantumbutterfly Avatar asked Oct 28 '25 14:10

quantumbutterfly


2 Answers

It's one of the (rare) use-cases for an anonymous function:

>>> sorted([[1, 'C'], [2, 'D'], [3, 'a'], [4, 'b']], key=lambda x: x[1].lower())
[[3, 'a'], [4, 'b'], [1, 'C'], [2, 'D']]

Lambdas are generally a bit clunky and unpythonic, but unfortunately, there is no "compose" function built-in to python.

like image 140
wim Avatar answered Oct 31 '25 03:10

wim


Either a lambda:

sorted(unsortedlist, key=lambda x: x[1].lower())

or a regular function:

def my_key(x):
    return x[1].lower()

sorted(unsortedlist, key=my_key)
like image 35
Zero Piraeus Avatar answered Oct 31 '25 05:10

Zero Piraeus



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!