zoukankan      html  css  js  c++  java
  • Python reduce() 函数

    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)
    
  • 相关阅读:
    Swift # Apple Pay集成
    GitHub Top 100 简介
    一些常用算法
    CocoaPods 建立私有仓库
    安装 CocoaPods & Alcatraz
    iOS程序 # 启动过程
    Apache & WebDav 配置(二)
    SVN & Git (二)
    SVN & Git (一)
    poj 3169 Layout (差分约束)
  • 原文地址:https://www.cnblogs.com/863652104kai/p/11826421.html
Copyright © 2011-2022 走看看