欢迎访问宙启技术站
智能推送

Python中常用的高阶函数及其操作方法

发布时间:2023-07-01 17:16:19

高阶函数是指能接收其他函数作为参数,或者返回一个函数作为结果的函数。在Python中,有许多常用的高阶函数及其操作方法。

1. map(function, iterable):将函数 function 应用于 iterable 中的每个元素,并返回一个由结果组成的新列表。例如:

numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2, numbers))
# 输出 [1, 4, 9, 16, 25]

2. filter(function, iterable):使用函数 functioniterable 中的每个元素进行判断,返回满足条件的元素组成的新列表。例如:

numbers = [1, 2, 3, 4, 5]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
# 输出 [2, 4]

3. reduce(function, iterable[, initializer]):使用函数 functioniterable 中的元素进行累积计算,返回一个最终的结果值。例如:

from functools import reduce

numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
# 输出 120

4. sort(iterable[, key][, reverse]):对 iterable 中的元素进行排序。key 参数可设置为一个函数,用于确定排序的依据;reverse 参数可设置为 True,按降序进行排序。例如:

numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5]
numbers.sort(reverse=True)
# 输出 [9, 6, 5, 5, 4, 3, 2, 1, 1]

5. sorted(iterable[, key][, reverse]):与 sort() 类似,但不会修改原始列表,而是返回一个新的排序列表。例如:

numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5]
sorted_numbers = sorted(numbers)
# 输出 [1, 1, 2, 3, 4, 5, 5, 6, 9]

6. zip(*iterables):将多个可迭代对象按元素进行打包,返回一个由元组组成的新列表。例如:

numbers = [1, 2, 3]
letters = ['a', 'b', 'c']
zipped = list(zip(numbers, letters))
# 输出 [(1, 'a'), (2, 'b'), (3, 'c')]

7. enumerate(iterable, start=0):对 iterable 中的元素进行编号,返回一个由元组 (index, element) 组成的新列表。例如:

letters = ['a', 'b', 'c']
enumerated = list(enumerate(letters))
# 输出 [(0, 'a'), (1, 'b'), (2, 'c')]

# 也可以通过设置起始编号
enumerated = list(enumerate(letters, start=1))
# 输出 [(1, 'a'), (2, 'b'), (3, 'c')]

以上是Python中常用的一些高阶函数及其操作方法,它们能够在处理数据时提供一定的方便性和灵活性。掌握这些函数的用法对于编写高效、简洁且可读性强的代码非常重要。