-1

你如何在python中对元组列表列表进行排序

例如:注意元组的最后一个元素是相同的

a  = [

[(1, 5, 6), (2, 2, 6), (3, 6, 6)],
[(6, 1, 3), (5, 7, 3), (4, 1, 3)],
[(5, 7, 2), (7, 5, 2), (6, 3, 2)],
[(9, 1, 7), (1, 5, 7), (2, 6, 7)]

]

我想使用元组的最后一个元素作为键进行排序。所以预期的结果是

[

[(5, 7, 2), (7, 5, 2), (6, 3, 2)],
[(6, 1, 3), (5, 7, 3), (4, 1, 3)],
[(1, 5, 6), (2, 2, 6), (3, 6, 6)],
[(9, 1, 7), (1, 5, 7), (2, 6, 7)]

]
4

2 回答 2

4

使用key参数进行排序和lambda函数

a.sort(key=lambda x: x[-1][-1]). # sorts in-place
sorted(a, key=lambda x: x[-1][-1]). # new sorted list

编辑:根据您要查看比较的元组更改第一个索引。即,用于x[0][-1]基于第一个元组进行比较

于 2013-04-24T23:31:32.650 回答
4
In [27]: a  = [
   ....:
   ....: [(1, 5, 6), (2, 2, 6), (3, 6, 6)],
   ....: [(6, 1, 3), (5, 7, 3), (4, 1, 3)],
   ....: [(5, 7, 2), (7, 5, 2), (6, 3, 2)],
   ....: [(9, 1, 7), (1, 5, 7), (2, 6, 7)]
   ....:
   ....: ]
                               # any tuple (first will do), last element
In [28]: a.sort(key=lambda l: l[0][-1])

In [29]: a
Out[29]:
[[(5, 7, 2), (7, 5, 2), (6, 3, 2)],
 [(6, 1, 3), (5, 7, 3), (4, 1, 3)],
 [(1, 5, 6), (2, 2, 6), (3, 6, 6)],
 [(9, 1, 7), (1, 5, 7), (2, 6, 7)]]
于 2013-04-24T23:30:47.263 回答