python排序sorted與sort比較 (轉)

來源:互聯網
上載者:User

標籤:logs   world   lam   http   序列   rabl   列表   指定   全域   

 

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=[]

原文地址:https://www.cnblogs.com/MrFiona/p/5958918.html

python排序sorted與sort比較 (轉)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.