7高阶函数sorted

"""
sorted()
运行原理:
把可迭代数据里面的元素,一个个的拿出来,放到key这个函数在进行处理,
并安装函数中retrun的结果进行排序,返回一个新列表
功能: 排序
参数:
iterable 可迭代的数据
reverse 可选,是否反转,默认为False不反转, True反转
key 可选, 函数,可以是自定义函数,或内建函数

返回值: 排序后的结果
"""

sorted 的三种方法

1从小到大排序

arr = [32,54,5,-21,3,2,5]
res = sorted(arr)
print(res)


E:\python3810\python.exe D:/py/test/gao/函数-sorted.py
[-21, 2, 3, 5, 5, 32, 54]

2reverse=True 从大到小排序

arr = [32,54,5,-21,3,2,5]
res = sorted(arr,reverse=True)
print(res)

E:\python3810\python.exe D:/py/test/gao/函数-sorted.py
[2, 3, -5, 21, 32, 54]

3使用abs函数(求绝对值),作为sorted的key关键字参数使用

arr = [32, 54, -5, 21, 3, 2]
res = sorted(arr, key=abs)
print(res)

E:\python3810\python.exe D:/py/test/gao/函数-sorted.py
[2, 3, -5, 21, 32, 54]

4使用自定义函数,当作key的关键字参数

def func(num):
    return num % 4

arr = [32,54,5,21,3,2,5]

# 在sorted函数中使用自定义函数对数据进行出来处理
res = sorted(arr,key=func)
print(res)

E:\python3810\python.exe D:/py/test/gao/函数-sorted.py
[32, 5, 21, 5, 54, 2, 3]

5使用匿名函数当作sorted的参数

arr = [32,54,5,21,3,2,5]
res = sorted(arr,key=lambda n:n%2)
print(res)

E:\python3810\python.exe D:/py/test/gao/函数-sorted.py
[32, 54, 2, 5, 21, 3, 5]
原文地址:https://www.cnblogs.com/john5yang/p/15631004.html