How can I efficiently and easily sort a list of tuples without being sensitive to case?
For example this:
[('a', 'c'), ('A', 'b'), ('a', 'a'), ('a', 5)]
Should look like this once sorted:
[('a', 5), ('a', 'a'), ('A', 'b'), ('a', 'c')]
The regular lexicographic sort will put 'A' before 'a' and yield this:
[('A', 'b'), ('a', 5), ('a', 'a'), ('a', 'c')]
You can use sort
's key
argument to define how you wish to regard each element with respect to sorting:
def lower_if_possible(x):
try:
return x.lower()
except AttributeError:
return x
L=[('a', 'c'), ('A', 'b'), ('a', 'a'), ('a', 5)]
L.sort(key=lambda x: map(lower_if_possible,x))
print(L)
See http://wiki.python.org/moin/HowTo/Sorting for an explanation of how to use key
.
list_of_tuples.sort(key=lambda t : tuple(s.lower() if isinstance(s,basestring) else s for s in t))
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