Python中四大高阶函数,你认识几个?

作者:微信公众号:【架构师老卢】
11-21 19:10
297

下面我将详细讲解Python中四大高阶函数(匿名函数、map函数、sorted函数、reduce函数、filter函数)的功能及使用方法,并提供相应的实例源代码。

1. 匿名函数(lambda函数)

匿名函数是一种通过lambda关键字定义的小型、临时的函数。它通常用于一次性的简单操作。

# 示例1:计算两个数的和
add = lambda x, y: x + y
result = add(3, 5)
print(result)  # 输出 8

# 示例2:筛选出列表中的偶数
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  # 输出 [2, 4, 6, 8]

2. map函数

map函数用于对可迭代对象的每个元素应用一个函数,返回一个新的可迭代对象。

# 示例:将列表中的每个元素求平方
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2, numbers))
print(squared_numbers)  # 输出 [1, 4, 9, 16, 25]

3. sorted函数

sorted函数用于对可迭代对象进行排序。

# 示例1:对列表进行升序排序
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # 输出 [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

# 示例2:对字符串列表按长度进行排序
words = ['apple', 'banana', 'kiwi', 'orange']
sorted_words = sorted(words, key=lambda x: len(x))
print(sorted_words)  # 输出 ['kiwi', 'apple', 'banana', 'orange']

4. reduce函数

reduce函数在Python 3中被移到functools模块中,它对可迭代对象中的元素进行累积操作。

from functools import reduce

# 示例:计算列表中所有元素的乘积
numbers = [2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print(product)  # 输出 120

5. filter函数

filter函数用于过滤可迭代对象中的元素,返回一个满足条件的元素的迭代器。

# 示例:筛选出列表中的正数
numbers = [1, -2, 3, -4, 5, -6]
positive_numbers = list(filter(lambda x: x > 0, numbers))
print(positive_numbers)  # 输出 [1, 3, 5]

这些高阶函数在实际编程中经常用于简化代码、提高可读性,尤其是在处理数据集合时更为常见。

相关留言评论
昵称:
邮箱: