python中sorted()函數的應用

來源:互聯網
上載者:User

標籤:sorted函數   python   

1、sorted()函數的應用

  • sorted()函數可以接受一個參數
  • sorted()函數還可以接受一個key函數來實現自訂的排序。
  • sorted()還可以接受第三個參數:reverse=True,來實現反序排列
  • 接受一個參數的例子如下:
    sorted([5,-3,1])——————->結果[-3,1,5] 按大小進行排序
  • 接受兩個參數:除了要接收要排序的資料,還可以接收一個函數來滿足此函數的要求進行排序,例如:sorted([5,-3,1],key=abs)————–>結果:[1,-3,5]

練習題:將d=[(‘wu’,98),(‘rang’,89),(‘hao’,76)] 按名字和分數分別進行排序

代碼如下:

#coding:UTF-8def my_name(t):    return t[0]def my_score(t):    return t[1]#測試d=[(‘wu‘,98),(‘rang‘,89),(‘hao‘,76)]#按名字進行排序l1=sorted(d,key=my_name)print("by_name sorted:",l1)l2=sorted(d,key=my_score)print("by_score sorted",l2)

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

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.