zoukankan      html  css  js  c++  java
  • Python的functools.reduce用法

    python 3.0以后, reduce已经不在built-in function里了, 要用它就得from functools import reduce.

    reduce的用法

    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.

    意思就是对sequence连续使用function, 如果不给出initial, 则第一次调用传递sequence的两个元素, 以后把前一次调用的结果和sequence的下一个元素传递给function. 如果给出initial, 则第一次传递initial和sequence的第一个元素给function.

    1
    2
    3
    4
    5
    6
    7
    from functools import reduce 
    reduce(lambda x,y: x+y, [123]) 
    输出 6 
    reduce(lambda x, y: x+y, [1,2,3], 9
    输出 15 
    reduce(lambda x,y: x+y, [123], 7
    输出 13 
  • 相关阅读:
    UI自动化测试框架
    Pyse( selenium-api的二次封装)
    Selenium之webdriverAPI
    selenium 基础之定位方式
    html综合应用
    html基础之js操作
    html基础之Dom操作
    (九)Locust 参数化
    (八)Locust 设置断言
    (七)Locust 的类和方法
  • 原文地址:https://www.cnblogs.com/liuys635/p/11222499.html
Copyright © 2011-2022 走看看