Overview

用來排序可迭代物件中的元素。可以利用關鍵字參數 key 來指定排序的參考,透過 lambda 自訂要排序的目標。

Usage

語法:sorted(iterable, key=function)

a = [
    ['qqqq', 1111],
    ['aaaa', 2222],
    ['zzzz', 3333]
]

sort0 = sorted(a, key=lambda x: x[0])
sort1 = sorted(a, key=lambda x: x[1])
sort11 = sorted(a, key=lambda x: x[1], reverse=True)
print(sort0)  # [['aaaa', 2222], ['qqqq', 1111], ['zzzz', 3333]]
print(sort1)  # [['qqqq', 1111], ['aaaa', 2222], ['zzzz', 3333]]
print(sort11)  # [['zzzz', 3333], ['aaaa', 2222], ['qqqq', 1111]]

Reference