4

我有一个元组列表

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

我想按字母顺序(并且区分大小写)来得到这个:

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

我试过这个:

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

不幸的是,我得到了这个:

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

2 回答 2

9

包括一个指示第一个字符是否为大写的键:

>>> 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先排序,True所以首字母小写的单词将排在首字母大写的单词之前。单词按字典顺序排序。

于 2013-03-08T12:57:19.613 回答
0

Define your own sort function:

Characters are compared by their ascii values and therefore 'A'(65) is always smaller than 'a'(97), but you can change this by returning smaller 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)]
于 2013-03-08T13:03:31.853 回答