Python中sort()和sorted()的區別

來源:互聯網
上載者:User

標籤:style   pytho   16px   logs   lis   code   orm   區別   返回鍵   

1、sort()是可變對象(字典)的方法,無參數無返回值,  sort()會改變可變對象,因此無需傳回值。例如:

list:

1 >>> a = [4,3,7,8]2 >>> a.sort()3 >>> a4 [3, 4, 7, 8]

即sort()直接將可變對象的值給改變了。

 

2、sorted()是python的內建函數,並不是可變對象(列表、字典)的特有方法,sorted()函數需要一個參數(參數可以是列表、字典、元組、字串),無論傳遞什麼參數,都將返回一個以列表為容器的傳回值,如果是字典將返回鍵的列表。

list:

1 >>> a = [4,3,7,8]2 >>> sorted(a)3 [3, 4, 7, 8]4 >>> a5 [4, 3, 7, 8]

即sorted會返會一個list副本,同時將原來list的值改變了可將這個返回的值賦給其他變數。

 

dict:

1 >>> b = {1:‘ab‘,2:‘degg‘,4:‘ght‘,9:‘d‘}2 >>> sorted(b)3 [1, 2, 4, 9]4 >>> b5 {1: ‘ab‘, 2: ‘degg‘, 4: ‘ght‘, 9: ‘d‘}

即sorted(dict)時,是按key排序,同時將key返回成一個列表。

 

Python中sort()和sorted()的區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.