python 函数 —— list.sort()

sort(*, key=None, reverse=None)
This method sorts the list in place, using only < comparisons between items. Exceptions are not suppressed - if any comparison operations fail, the entire sort operation will fail (and the list will likely be left in a partially modified state).


sort() accepts two arguments that can only be passed by keyword (keyword-only arguments):
sort() 方法接受 两个参数,只能通过 keywords 进行传递。


key specifies a function of one argument that is used to extract a comparison key from each list element (for example, key=str.lower). The key corresponding to each item in the list is calculated once and then used for the entire sorting process. The default value of None means that list items are sorted directly without calculating a separate key value.

The functools.cmp_to_key() utility is available to convert a 2.x style cmp function to a key function.

reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

This method modifies the sequence in place for economy of space when sorting a large sequence. To remind users that it operates by side effect, it does not return the sorted sequence (use sorted() to explicitly request a new sorted list instance).

The sort() method is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade).

CPython implementation detail: While a list is being sorted, the effect of attempting to mutate, or even inspect, the list is undefined. The C implementation of Python makes the list appear empty for the duration, and raises ValueError if it can detect that the list has been mutated during a sort.

In [135]: a = ['x11','abc323','e26','112ddd']

In [136]: a
Out[136]: ['x11', 'abc323', 'e26', '112ddd']

In [137]: a.sort()

In [138]: a
Out[138]: ['112ddd', 'abc323', 'e26', 'x11']

In [139]: a.sort(key=len, reverse=True)

In [140]: a
Out[140]: ['112ddd', 'abc323', 'e26', 'x11']

In [141]: a.sort(key=lambda x:x[-1], reverse=True)

In [142]: a
Out[142]: ['112ddd', 'e26', 'abc323', 'x11']

In [144]: ord('1')
Out[144]: 49

In [145]: ord('e')
Out[145]: 101

key 将应用于 list 中的每一个元素

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值