python排序列表基于内部元素和忽略大小写的列表

时间:2015-03-19 22:40:03

标签: python sorting ignore-case

让我们说我在python中有以下列表

[ [1,"C"], [2, "D"], [3,"a"], [4,"b"] ]

我想按字母对列表进行排序,以便

[ [3,"a"], [4,"b"], [1,"C"], [2, "D"] ]

按内在字符排序,我会sorted(unsortedlist, key=itemgetter(1)) 要忽略大小写,我会sorted(unsortedlist, key=str.lower)

如何按内部元素排序并同时忽略大小写?

2 个答案:

答案 0 :(得分:5)

它是匿名函数的(罕见)用例之一:

>>> sorted([[1, 'C'], [2, 'D'], [3, 'a'], [4, 'b']], key=lambda x: x[1].lower())
[[3, 'a'], [4, 'b'], [1, 'C'], [2, 'D']]

Lambda通常有点笨拙和unpythonic,但是unfortunately, there is no "compose" function built-in to python

答案 1 :(得分:4)

要么是lambda:

sorted(unsortedlist, key=lambda x: x[1].lower())

或常规功能:

def my_key(x):
    return x[1].lower()

sorted(unsortedlist, key=my_key)