我有一个列表的列表。例如,

[
[0,1,'f'],
[4,2,'t'],
[9,4,'afsd']
]

如果我想通过内部列表的字符串字段对外部列表进行排序,在python中如何做到这一点?


当前回答

在适当的位置

>>> l = [[0, 1, 'f'], [4, 2, 't'], [9, 4, 'afsd']]
>>> l.sort(key=lambda x: x[2])

未在使用sorted的位置:

>>> sorted(l, key=lambda x: x[2])

其他回答

确保要排序的列表中没有任何null或NaN值。如果有NaN值,那么排序将被关闭,影响非空值的排序。

查看Python: sort函数在nan存在时的中断

还可以通过lambda函数实现多个标准

sorted_list = sorted(list_to_sort, key=lambda x: (x[1], x[0]))

使用一个自定义键函数,你可以很容易地排序任何列表的列表,因为你想:

L = [[0,1,'f'], [4,2,'t'], [9,4,'afsd']]

def sorter(lst):
    return lst[2].casefold()

L.sort(key=sorter)

# result: [[9, 4, 'afsd'], [0, 1, 'f'], [4, 2, 't']]

对多维数组排序[此处执行][1]

points=[[2,1],[1,2],[3,5],[4,5],[3,1],[5,2],[3,8],[1,9],[1,3]]

def getKey(x):
   return [x[0],-x[1]]

points.sort(key=getKey)

print(points)

更容易理解(Lambda实际上在做什么):

ls2=[[0,1,'f'],[4,2,'t'],[9,4,'afsd']]
def thirdItem(ls):
    #return the third item of the list
    return ls[2]
#Sort according to what the thirdItem function return 
ls2.sort(key=thirdItem)