python排序sorted與sort比較


Python list內置sort()方法用來排序,也可以用python內置的全局sorted()方法來對可迭代的序列排序生成新的序列。

sorted(iterable,key=None,reverse=False),返回新的列表,對所有可迭代的對象均有效

sort(key=None,reverse=False) 就地改變列表  reverse:True反序;False 正序

 

Example1:

>>>sorted([1,5,3,2,9])

[1,2,3,5,9]

>>>a=[5,3,2,1,4]

>>>a.sort()

>>>a

[1,2,3,4,5]   #若用list.sort()則list本身將被修改

>>>sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})

[1,2,3,4,5]   #sorted()對所有的可迭代序列都有效

在python2.4開始,list.sort()和sorted()增加key參數來指定一個函數,此函數在每個元素比較前被調用。

Example2:

>>>sorted("This is a test string from Andrew".split(), key=str.lower)  #加了key,忽略大小寫

['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']                 #key=len按照長度進行排序

>>>sorted("This is a test string from Andrew".split())    #未加key,默認大寫在前,小寫在后

['Andrew', 'This', 'a', 'from', 'is', 'string', 'test']

更多的情況是用復雜對象的某些值來對復雜對象進行排序。

Example3:

>>> student_tuples = [('john', 'A', 15),('jane', 'B', 12),('dave', 'B', 10),]

>>> sorted(student_tuples, key=lambda student: student[2])   # sort by age

[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

>>>student_tuples.sort(key=lambda x: x[2])

[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

 

Example4:

>>>s=”Hello79351WorldMyNameIsMrFiona0352231964”

>>>''.join(sorted(s,key=lambda x: (x.isdigit(),x.isdigit() and int(x)%2==0,x.islower(),x.isupper(),x)))

'FHIMMNWaadeeilllmnooorrsy113335579902246'

大寫在前,小寫在后,數字放在最后並且奇數在偶數之前

>>>s={‘a’:10,’t’:5,’c’:2,’b’:12}

>>>sorted(s,key=lambda x:x[0])

[‘a’,’b’,’c’,’t’]

>>>s=[]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM