Python 3 内置函数 - `sorted()`函数

Python 3 内置函数 - sorted()函数

0. sorted() 函数

对所有可迭代的对象进行排序操作。

  • reverse = True: 反向排序。

1. 使用方法

>>> help(sorted)
# output:
Help on built-in function sorted in module builtins:

## 使用方法
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 customize the sort order, and the
    reverse flag can be set to request the result in descending order.

2. 使用示例

示例1.

>>> a = [5, 0, 1, 2, 3, 4]
>>> sorted(a)
# output:
[0, 1, 2, 3, 4, 5]

示例2.

>>> a = [5, 0, 1, 2, 3, 4]
>>> a, sorted(a, reverse=True)   # 反向排序
# output:
([5, 0, 1, 2, 3, 4], [5, 4, 3, 2, 1, 0])  # 不改变原列表。

3. 区别 sort()

利用 listsort 排序,这个方法会修改原始的 list

>>> a = [5, 0, 1, 2, 3, 4]
>>> a.sort()
>>> a
# output:
[0, 1, 2, 3, 4, 5]

逆序排序。

>>> a = [5, 0, 1, 2, 3, 4]
>>> a.sort(reverse=True)
>>> a
# output:
[5, 4, 3, 2, 1, 0]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值