2023-10-24 22:45:23
Python中常用的高阶函数包括map、filter、sorted和reduce,它们均接受函数作为参数,用于简化代码并提升可读性。以下是对这些函数的详细说明及示例:
1. map函数功能:将函数应用于可迭代对象的每个元素,返回迭代器。示例:
lst = [1, 2, 3, 4, 5]# 将元素转为字符串result = list(map(str, lst)) # 输出: ['1', '2', '3', '4', '5']# 多参数函数示例lst2 = [10, 100, 1000]result = list(map(lambda x, y: x + y, lst, lst2)) # 输出: [11, 102, 1003]2. filter函数功能:根据函数返回的布尔值过滤可迭代对象,保留为True的元素。示例:
# 保留奇数numbers = [1, 2, 3, 4, 5]result = list(filter(lambda x: x % 2 != 0, numbers)) # 输出: [1, 3, 5]# 过滤空值或无效数据lst = ['A', '', 'B', None, 'C', ' ', 'a', 1, 0]result = list(filter(lambda x: x and str(x).strip(), lst)) # 输出: ['A', 'B', 'C', 'a', 1]3. sorted函数功能:对可迭代对象排序,可通过key参数自定义规则。示例:
# 忽略大小写排序字符串words = ['bob', 'about', 'Zoo', 'Credit']result = sorted(words, key=lambda x: x.lower()) # 输出: ['about', 'bob', 'Credit', 'Zoo']# 按字典值排序d = {"a": 3, "b": 4, "c": 2, "d": 5}result = dict(sorted(d.items(), key=lambda x: x[1])) # 输出: {'c': 2, 'a': 3, 'b': 4, 'd': 5}# 复杂排序:正数在前且升序,负数在后且降序nums = [7, -8, 5, 4, 0, -2, -5]result = sorted(nums, key=lambda x: (x <= 0, abs(x))) # 输出: [0, 4, 5, 7, -2, -5, -8]4. reduce函数功能:累积计算可迭代对象,需从尺早functools导入。示例:
from functools import reduce# 计陵让雀算阶乘滑者n = [1, 2, 3, 4, 5]result = reduce(lambda x, y: x * y, n) # 输出: 120# 数字列表转字符串nums = [1, 4, 5, 9]result = reduce(lambda x, y: str(x) + str(y), nums) # 输出: '1459'综合练习示例掌握这些高阶函数能显著提升代码简洁性与效率,尤其在数据处理和函数式编程场景中。