Python 常用排序函数
注意列表的 sort() 方法会直接操作列表本身, 返回为 None
L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
也可以使用 sorted
内置函数, 不过 sorted 函数不改变原列表, 会返回一个新创建的列表
sorted(iterable, key=None, reverse=False)
Return a new list containing all items from the iterable in ascending order.
A custom key function can be supplied to customise the sort order, and the
reverse flag can be set to request the result in descending order.
例子
对 tuple 进行排序,先按照第一个元素升序,如果第一个元素相同,再按照第二个元素降序排列。
L = [(12, 12), (34, 13), (32, 15), (12, 24), (32, 64), (32, 11)]
L.sort(key=lambda x: (x[0], -x[1]))
print(L)