Sort the list of tuples in alphabetical order (case sensitive)

I have a list of tuples

alist = [(u'First', 23), (u'Second', 64),(u'last', 19)] 

I want to sort alphabetically (and case sensitive) to get this:

 (u'last', 19), (u'First', 23), (u'Second', 64) 

I tried this:

 sorted(alist, key=lambda x: x[0], reverse= True) 

Unfortunately, I get the following:

 (u'last', 19), (u'Second', 64), (u'First', 23), 
+4
source share
2 answers

Include a key that indicates whether the first character is uppercase or not:

 >>> sorted([(u'First', 23), (u'Second', 64),(u'last', 19)], key=lambda t: (t[0][0].isupper(), t[0])) [(u'last', 19), (u'First', 23), (u'Second', 64)] 

False sorts before True , so words with a lowercase initial image will be sorted before words with an initial capital. Words are otherwise sorted lexicographically.

+9
source

Define your own sort function:

Characters are compared by their ascii values, so 'A' (65) is always less than 'A' (97), but you can change this by returning a lower value for 'A' compared to 'A' .

 In [39]: lis=[(u'First', 23),(u'laSt',1), (u'Second', 64),(u'last', 19),(u'FirSt',5)] In [40]: def mysort(x): elem=x[0] return [ord(x)-97 if x.islower() else ord(x) for x in elem] ....: In [41]: sorted(lis,key=mysort) Out[41]: [(u'last', 19), (u'laSt', 1), (u'First', 23), (u'FirSt', 5), (u'Second', 64)] 
0
source

All Articles