Python3-筆記-C-005-函數-sorted

來源:互聯網
上載者:User

標籤:span   iterable   ever   lam   style   字母   排序   font   大寫   

# sorted(iterable,key=None,reverse=False)
# key接受一個函數,這個函數只接受一個元素,預設為None
# reverse是一個布爾值。預設為False排在前,True排在後,升序,即合格往後排

# 按照年齡來排序
students = [(‘john‘, ‘A‘, 15), (‘jane‘, ‘B‘, 12), (‘dave‘,‘B‘, 10)]
r1 = sorted(students, key=lambda s: s[2])
# <class ‘list‘>: [(‘dave‘, ‘B‘, 10), (‘jane‘, ‘B‘, 12), (‘john‘, ‘A‘, 15)]


# 字串排序,定序:小寫<大寫<奇數<偶數
s = ‘asdf234GDSdsf23‘
r3 = "".join(sorted(s, key=lambda x: (x.isdigit())))
# 數字在後 ‘asdfGDSdsf23423‘
r4 = "".join(sorted(s, key=lambda x: (x.isdigit(), x.isdigit() and int(x) % 2 == 0)))
# 數字在後,偶數在後 ‘asdfGDSdsf33242‘
r5 = "".join(sorted(s, key=lambda x: (x.isdigit(),x.isdigit() and int(x) % 2 == 0, x.isupper())))
# 數字在後,偶數在後,大寫在後 ‘asdfdsfGDS33242‘
r6 = "".join(sorted(s, key=lambda x: (x.isdigit(),x.isdigit() and int(x) % 2 == 0, x.isupper(), x)))
# 數字在後,偶數在後,大寫在後,按字母或數字升序排 ‘addffssDGS33224‘


# 正數在前負數在後,正數從小到大,負數從大到小
list1 = [4, -8, 7, 5, 0, -2, -5]
r1 = sorted(list1, key=lambda x: (x < 0))
# 先按照正負排先後,將負數移到後面 <class ‘list‘>: [4, 7, 5, 0, -8, -2, -5]
r2 = sorted(list1, key=lambda x: (x < 0, abs(x)))
# 再按照大小排先後 <class ‘list‘>: [0, 4, 5, 7, -2, -5, -8]

Python3-筆記-C-005-函數-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.