Sort the list of tuples without case sensitivity

How can I efficiently and easily sort a list of tuples without being case sensitive?

For instance:

[('a', 'c'), ('A', 'b'), ('a', 'a'), ('a', 5)]

Should look like once sorted:

[('a', 5), ('a', 'a'), ('A', 'b'), ('a', 'c')]

Regular lexicographic sorting will place 'A' in front of 'a' and give the following:

[('A', 'b'), ('a', 5), ('a', 'a'), ('a', 'c')]
+5
source share
5 answers

You can use an argument sort keyto determine how you want to treat each item in terms of 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 it key.

+10
source
list_of_tuples.sort(key=lambda t : tuple(s.lower() if isinstance(s,basestring) else s for s in t))
+2

- :

def sort_ci(items):
    def sort_tuple(tuple):
        return ([lower(x) for x in tuple],) + tuple
    temp = [sort_tuple(tuple) for tuple in items]
    temp.sort()
    return [tuple[1:] for tuple in temp]

, , , , . .

, sort, .

0

, , " " Python (http://wiki.python.org/moin/HowTo/Sorting/).

# Create a list of new tuples whose first element is lowercase
# version of the original tuple.  I use an extra function to
# handle tuples which contain non-strings.
f = lambda x : x.lower() if type(x)==str else x
deco = [(tuple(f(e) for e in t), t) for t in ex]

# now we can directly sort deco and get the result we want
deco.sort()

# extract the original tuples in the case-insensitive sorted order
out = [t for _,t in deco]
0

:

list_of_tuples.sort(key=lambda t : tuple(t[0].lower()))

( t [0] , , )

0

All Articles