0
点赞
收藏
分享

微信扫一扫

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

两岁时就很帅 2022-03-20 阅读 48
python

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

0. sorted() 函数

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 条评论