How do you use the reduce() function in Python?
The reduce() function is used to perform a cumulative calculation on a sequence. It takes a function and a sequence as parameters, and returns a single value.
Here is how to use the reduce() function:
from functools import reduce
# 定义一个累加函数
def add(x, y):
return x + y
# 使用 reduce() 函数对序列进行累加计算
result = reduce(add, [1, 2, 3, 4, 5])
print(result) # 输出结果为 15
In the example above, the reduce() function is first imported from functools. Then, a cumulative function add(x, y) is defined that takes two parameters and returns their sum. Finally, the reduce() function is used to apply the add() function to the sequence [1, 2, 3, 4, 5], resulting in 15.