Skip to content

高阶函数 - 20240718

将函数作为返回值的函数被称为高阶函数

map(func, iter)

Iterable 便利并传入函数, 以其返回值构建新的 Iterable

示例:

python
map(lambda x: x * 2, [1, 2, 3, 4])  # 返回值是 MapObject, list(MapObject) == [2, 4, 6, 8]

filter(func, iter)

过滤 Iterable 并返回一个新的 Iterable

示例:

python
filter(lambda x: not (x % 2), [1, 2, 3, 4])  # 返回值是 FilterObject, list(FilterObject) == [2, 4]

sorted(iter, *, key=None, reverse=False)

排序 Iterable 并返回排序后的新的 Iterable

示例:

python
sorted([4, 3, 6, 2])  # 返回值是传入 `Iterable` 的类型, == [2, 3, 4, 6]
sorted([4, 3, 6, 2], reverse=True)  # 返回值是传入 `Iterable` 的类型, 反转后 == [6, 4, 3, 2]
sorted({'a': 1, 'b': 3, 'c': 2}.items(), key=lambda tup: tup[1])  # 返回值是 list (不可索引的 `Iterable` 会被转换为 `list`), == [('a', 1), ('c', 2), ('b', 3)], dict(it) == {'a': 1, 'c': 2, 'b': 3}

max(*args) / min(*args)

获取 Iterable 最大/最小值

lambda args: experssion of return value

创建匿名函数