Python 内建函数 - sorted(iterable[, key][, reverse])

Python 的 sorted() 内建函数用于返回一个排序后的列表。它可以接受 key 函数来定制排序依据,以及 reverse 参数用于降序排序。排序是稳定的,即相等的元素保持原有顺序。示例包括基本排序、key 函数应用以及使用 operator 模块进行复杂排序。
摘要由CSDN通过智能技术生成

Manual

Return a new sorted list from the items in iterable.

Has two optional arguments which must be specified as keyword arguments.

key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).

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

Use functools.cmp_to_key() to convert an old-style cmp function to a key function.

The built-in sorted() function 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).

For sorting examples and a brief sorting tutorial, see Sorting HOW TO.

直译

根据iterable中的项返回一个新排序的列表。

这里有两个可选参数,其必须指定为关键字参数。

  • key指定某个参数的函数,它可以用于从每个列表元素中提取比较键,例如key=str.lower。默认值为None(直接比较元素)。
  • reverse是一个布尔值,如果设置为True,列表的元素会将每个比较反置进行排列。

内建sorted()函数可以保证稳定,如果它保证不改变元素的相对顺序,那么排序就是稳定的。相对顺序的比较恒等,对于多次传递下的排序很有用(例如:按部门排序,然后按工资等级排序)

实例

实例摘自官方手册

基本排序

# 简单排序
>>> sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5]
# list.sort()方法,该方法仅对列表定义。
>>> a = [5, 2, 3, 1, 4]
>>> a.sort()
>>> a
[1, 2, 3, 4, 5]
# sorted()支持任何迭代形式
>>> sorted({
  1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})
[1, 2, 3, 4, 5]

key函数

list.sort()和sorted()都有key参数,用来指定一个函数,并对每个列表元素对象调用该函数进行比较。

# 小写字符串比较,key=str.lower
>>> sorted("This is a test string from Andrew".split(), key=str.lower)
['a', 'Andrew', 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值