Python内置了一些非常有用的高阶函数,这些函数可以接受其他函数作为参数或将函数作为返回值。以下是Python中一些常用的高阶函数及其使用示例:
1. map()
map()
函数接收两个参数,一个是函数,一个是可迭代对象(如列表),将传入的函数依次作用到可迭代对象的每个元素,并把结果作为新的迭代器返回。
def square(x):
return x ** 2
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(square, numbers)
print(list(squared_numbers)) # 输出: [1, 4, 9, 16, 25]
2. filter()
filter()
函数用于过滤序列,接收一个函数和一个序列作为参数,把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。
def is_even(x):
return x % 2 == 0
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(is_even, numbers)
print(list(even_numbers)) # 输出: [2, 4, 6]
3. reduce()
reduce()
函数在functools
模块中,它会对参数序列中元素进行累积。
from functools import reduce
def add(x, y):
return x + y
numbers = [1, 2, 3, 4, 5]
sum_of_numbers = reduce(add, numbers)
print(sum_of_numbers) # 输出: 15
4. sorted()
sorted()
函数可以对所有可迭代的对象进行排序操作。
numbers = [3, 1, 4, 1, 5, 9]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # 输出: [1, 1, 3, 4, 5, 9]
# 按照绝对值大小排序
numbers = [-2, -1, 0, 1, 2]
abs_sorted_numbers = sorted(numbers, key=abs)
print(abs_sorted_numbers) # 输出: [0, -1, 1, -2, 2]
5. lambda
表达式
lambda
是一个匿名函数,常用于高阶函数中作为参数传递。
# 使用lambda表达式进行排序
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
print(pairs) # 输出: [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
6. max()
和 min()
max()
和 min()
函数可以接受一个函数作为 key 参数,用于决定排序的依据。
# 找出字典中值最大的键
data = {'a': 4, 'b': 3, 'c': 10, 'd': 1}
key_of_max_value = max(data, key=data.get)
print(key_of_max_value) # 输出: 'c'
# 找出字典中值最小的键
key_of_min_value = min(data, key=data.get)
print(key_of_min_value) # 输出: 'd'
7. all()
和 any()
all()
和 any()
用于检查可迭代对象中的所有元素或任意元素是否满足条件。
# all() 检查是否所有元素都为True
numbers = [1, 2, 3, 4, 5]
all_positive = all(n > 0 for n in numbers)
print(all_positive) # 输出: True
# any() 检查是否有任意元素为True
numbers = [0, 1, 2, 3, 4]
any_zero = any(n == 0 for n in numbers)
print(any_zero) # 输出: True
8. sum()
sum()
函数可以对可迭代对象中的元素进行求和。
# 求和
numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(total) # 输出: 15
# 使用start参数从特定值开始求和
total = sum(numbers, start=10)
print(total) # 输出: 25
9. zip()
zip()
函数用于将可迭代对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。
# 将两个列表组合成元组列表
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
combined = zip(names, ages)
print(list(combined)) # 输出: [('Alice', 25), ('Bob', 30), ('Charlie', 35)]
10. enumerate()
enumerate()
函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标。
# 列出列表元素及其索引
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(f"Index: {index}, Fruit: {fruit}")
# 输出:
# Index: 0, Fruit: apple
# Index: 1, Fruit: banana
# Index: 2, Fruit: cherry