iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 26
0
自我挑戰組

Python初學者的自學筆記系列 第 26

Day26排序

簡單的升序排序是非常容易的。只需要呼叫sorted()方法。它返回一個新的list

sorted([5, 2, 3, 1, 4])

結果:
[1, 2, 3, 4, 5]
又或者使用list.sort()方法來排序,這個方法會直接修改list

a = [5, 2, 3, 1, 4]
a.sort()
print(a)

結果: [1, 2, 3, 4, 5]
list.sort()和sorted()都接受一個引數reverse(True or False)來表示升序或降序排序。例如對上面的student降序排序如下:

student_tuples = [
        ('Amy', 'O', 15),
        ('Bruce', 'A', 12),
        ('dave','B', 10),
]
sorted(student_tuples, key=itemgetter(2), reverse=True)

結果:
[('Amy', 'O', 15), ('Bruce', 'A', 12), ('dave', 'B', 10)]

Natural Sort
如果要把書頁作排序

pages = ['p12', 'p3', 'p15', 'p25', 'p4', 'p6', 'p11', 'p1']
sorted(pages)

結果:
['p1', 'p11', 'p12', 'p15', 'p25', 'p3', 'p4', 'p6']
因為Python 使用 ASII 的方式排序,所以會這樣排列,但幸好 Python 擁有強大的第三方函式庫可以使用,所以我們可以選用 natsort 來解決這個問題,這個函式庫可以簡單的用 easy_install 或是 pip 下載。

from natsort import natsorted
pages = ['p12', 'p3', 'p15', 'p25', 'p4', 'p6', 'p11', 'p1']
natsorted(pages)

['p1', 'p3', 'p4', 'p6' 'p11', 'p12', 'p15', 'p25']


上一篇
Day25 itertools
下一篇
Day27物件導向
系列文
Python初學者的自學筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言