python中tuple构成的list的排序 - Waleking的专栏 - 博客频道 - CSDN.NET
tuple构成的list可以按照tuple中的任意一位进行排序。在python中的例子如下:[(13, 1), (11, 1), (9, 1), (6, 1), (1, 1), (2, 1), (4, 1), (13, 1), (4, 1), (2, 1), (13, 1), (0, 1), (7, 1), (11, 2), (9, 2), (6, 2), (1, 2), (2, 2), (13, 2), (2, 2), (8, 2), (12, 2), (13, 2), (0, 2), (7, 2), (4, 3), (13, 3), (5, 3), (5, 3), (4, 3), (6, 3)]要将上面的list按照tuple中的第一位升序排列:[(0, 1), (0, 2), (1, 1), (1, 2), (2, 1), (2, 1), (2, 2), (2, 2), (4, 1), (4, 1), (4, 3), (4, 3), (5, 3), (5, 3), (6, 1), (6, 2), (6, 3), (7, 1), (7, 2), (8, 2), (9, 1), (9, 2), (11, 1), (11, 2), (12, 2), (13, 1), (13, 1), (13, 1), (13, 2), (13, 2), (13, 3)]python中的方法是调用sorted函数,sorted函数可以指定key,用lambda关键字定义“单行最小函数”。单行最小函数是说在一行代码中定义函数,可以看作是内联函数。例子:>>> def f(x): ... return x*2 ... >>> f(3) 6 >>> g = lambda x: x*2 >>> g(3) 6 >>> (lambda x: x*2)(3) 6
- l=[(1,2),(2,5),(3,6),(2,7),(2,8)]
- sorted_l=sorted(l,key=lambda t:t[0])
- print(sorted_l)
- sorted_l=sorted(l,key=lambda t:t[1])
- print(sorted_l)
得到的结果是:[(1, 2), (2, 5), (2, 7), (2, 8), (3, 6)] #按照tuple的第一位排序[(1, 2), (2, 5), (3, 6), (2, 7), (2, 8)] #按照tuple的第二位排序