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)
    
  • 相关阅读:
    java线程学习之volatile关键字
    java线程学习之yield方法
    java线程学习之join方法
    小程序hideTarBar隐藏TabBar后,获取windowHeight不准确问题
    canvas等base64格式上传到服务端直传到oss
    服务器关于node的注意事项
    node.js连接本地数据库
    小程序(mpvue框架)的总结
    git代码的注意
    js里的实用小技巧
  • 原文地址:https://www.cnblogs.com/863652104kai/p/11826421.html
Copyright © 2011-2022 走看看