>>> list = [2,5,8,9,3] >>> list [2,5,8,9,3] >>> list.sort() >>> list [2, 3, 5, 8, 9]
>>> list = [2,5,8,9,3] >>> list [2,5,8,9,3] >>> sorted(list) [2, 3, 5, 8, 9]
>>>L = [2,3,1,4] >>>L.sort() >>>L >>>[1,2,3,4]
>>>L = [2,3,1,4] >>>L.sort(reverse=True) >>>L >>>[4,3,2,1]
>>>L = [('b',6),('a',1),('c',3),('d',4)]
>>>L.sort(lambda x,y:cmp(x[1],y[1]))
>>>L
>>>[('a', 1), ('c', 3), ('d', 4), ('b', 6)] >>>L = [('b',6),('a',1),('c',3),('d',4)]
>>>L.sort(key=lambda x:x[1])
>>>L
>>>[('a', 1), ('c', 3), ('d', 4), ('b', 6)] >>>L = [('b',2),('a',1),('c',3),('d',4)]
>>>import operator
>>>L.sort(key=operator.itemgetter(1))
>>>L
>>>[('a', 1), ('b', 2), ('c', 3), ('d', 4)] >>>L = [('b',2),('a',1),('c',3),('d',4)]
>>>A = [(x[1],i,x) for i,x in enumerate(L)] #i can confirm the stable sort
>>>A.sort()
>>>L = [s[2] for s in A]
>>>L
>>>[('a', 1), ('b', 2), ('c', 3), ('d', 4)] >>>L = [('d',2),('a',4),('b',3),('c',2)]
>>> L.sort(key=lambda x:x[1])
>>> L
>>>[('d', 2), ('c', 2), ('b', 3), ('a', 4)] >>> L = [('d',2),('a',4),('b',3),('c',2)]
>>> L.sort(key=lambda x:(x[1],x[0]))
>>> L
>>>[('c', 2), ('d', 2), ('b', 3), ('a', 4)] >>> L = [('d',2),('a',4),('b',3),('c',2)]
>>> L.sort(key=operator.itemgetter(1,0))
>>> L
>>>[('c', 2), ('d', 2), ('b', 3), ('a', 4)]
以上就是python list排序的两种方法及实例的详细内容,更多请关注Gxl网其它相关文章!
查看更多关于pythonlist排序的两种方法及实例的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did84133