Python reduce() 函数
在调用该函数之前,先要导入该函数from functools import reduce
def reduce(function, sequence, initial=None): # real signature unknown; restored from __doc__
"""
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
"""
pass
通俗解释:reduce(function, sequence)
: function是一个函数,sequence是一个数据集合(元组、列表等)。先将集合里的第1,2个参数参入函数执行,再将执行结果和第3个参数传入函数执行....,最终得到最后一个结果
比如:reduce(lambda x, y: x + y,[1,2,3,4])
执行步骤:
先将1,2传入:1+2 = 3
再将3,3传入:3+3 = 6
再将6,4传入:6+4 = 10
最终结果为:10
习题
Python 一个数如果恰好等于它的因子之和,这个数就称为"完数"。例如6=1+2+3.编程找出 1000 以内的所有完数
from functools import reduce
for i in range(2, 1001):
l = [1]
for j in range(2, int(i / 2 + 1)):
if i % j == 0:
l.append(j)
if i == reduce(lambda x,y: x+y, l):
print(i)