list.sort(func=None, key=None, reverse=False)
Python實例:
>>> list = [2,5,8,9,3] >>> list [2,5,8,9,3] >>> list.sort() >>> list [2, 3, 5, 8, 9]
Python實例:
>>> list = [2,5,8,9,3] >>> list [2,5,8,9,3] >>> sorted(list) [2, 3, 5, 8, 9]
物件,可以用作表達式。原來的list不變,產生一個新的排好序的list物件。
list.sort() 不會回傳對象,改變原有的list。 其他sort的實例:實例1:正向排序>>>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排序的兩種實例方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!