Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a list of tuples without case sensitivity

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')]
like image 640
David Underhill Avatar asked Mar 22 '10 18:03

David Underhill


2 Answers

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.

like image 134
unutbu Avatar answered Nov 05 '22 04:11

unutbu


list_of_tuples.sort(key=lambda t : tuple(s.lower() if isinstance(s,basestring) else s for s in t))
like image 30
PaulMcG Avatar answered Nov 05 '22 04:11

PaulMcG