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

时间:2013-04-24 23:28:03

标签: python list sorting python-2.7

如何在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)]

]

2 个答案:

答案 0 :(得分: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)]]

答案 1 :(得分: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]基于第一个元组进行比较