python 的sorted函數

來源:互聯網
上載者:User

標籤:dict   key   sort   表示   key值   AC   大小   可迭代對象   預設   

sorted函數:sorted(iterable,key,reverse)

其中iterable表示可以迭代的對象,例如可以是dict.items()、dict.keys()等,key是一個函數,用來選取參與比較的元素,reverse則是用來指定排序是倒序還是順序,reverse=true則是倒序,reverse=false時則是順序,預設時reverse=false

以下傳回值都是單一的key值排列或者value值排列

d = {‘Michael‘: 95, ‘Bob‘: 75, ‘Tracy‘: 85}>>>sorted(d.keys())[‘Bob‘, ‘Michael‘, ‘Tracy‘]>>>sorted(d.values())[75, 85, 95]>>>sorted(d)[‘Bob‘, ‘Michael‘, ‘Tracy‘]#預設就是根據key值排序>>>sorted(d,key=lambda x: d[x])#根據value值的大小對key排序[‘Bob‘, ‘Tracy‘, ‘Michael‘]

以下傳回值是既包含key又包含value的列表,與上面的區別就是sorted的第一個參數不是d而是d.items(),d.items會把d變成一個可迭代對象.

d = {‘Michael‘: 95, ‘Bob‘: 75, ‘Tracy‘: 85}>>>d.items()dict_items([(‘Michael‘, 95), (‘Bob‘, 75), (‘Tracy‘, 85)])>>>sorted(d.items(),key=lambda x : x[1])[(‘Bob‘, 75), (‘Tracy‘, 85), (‘Michael‘, 95)]>>>d = {‘data1‘:3,‘da‘:1,‘dat‘:2,‘data22‘:4,‘aa‘:3,‘ff‘:0}>>>sorted(d.items(),key=lambda x :(x[1],x[0]))#對dict先根據value排序,value相等的根據key排序[(‘ff‘, 0), (‘da‘, 1), (‘dat‘, 2), (‘aa‘, 3), (‘data1‘, 3), (‘data22‘, 4)]
sorted(d.items())#根據key值對整個dict排序
[(‘aa‘, 3), (‘da‘, 1), (‘dat‘, 2), (‘data1‘, 3), (‘data22‘, 4), (‘ff‘, 0)]

 

python 的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.