zoukankan      html  css  js  c++  java
  • python 的map和reduce(高阶函数)

    一、map()

    map()函数接受两个参数,一个是函数(f),一个是可迭代对象iterable ,map将传入的函数依次作用到序列的每个元素,并把结果作为新的迭代器iterator 返回

    例如:

    def f(x):
        return(x*x)
    
    r=map(f,[1,2,3,4,5])
    r  #是一个迭代器
    list(r)  #将r变成list 

    注意:参数中的f中含有2个参数会报错

    def f(x,y):
        return(x+y)
        
    r=map(f,([1,2,3,4,],[1,2,3,4]))
    r
    list(r)  #报错

    要记住map将传入的函数依次作用到序列的每个元素,是每个元素,这样可以做很多事情

    #可以简单地将list所有数字转为str
    list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))  #['1', '2', '3', '4', '5', '6', '7', '8', '9']

    二、reduce()

    reduce()函数接受两个参数,一个是函数(f必须接受两个参数),一个是可迭代对象iterable,reduce把前面2个元素作用于f,得到的结果再与下一个元素作用于f,直到最后一个元素

    reduce(f,[x1,x2,x3,x4])=f(f(f(x1,x2),x3),x4)

    from functools import reduce 
    def add(x,y):
        return(x+y)
    
    reduce(add,[1,2,3,4,5])  #序列求和
    
    
    
    from functools import reduce
    def fn(x,y):
        return(x*10+y)
    
    reduce(fn,[1,3,5,9])   #1359  将[1,3,5,9]变成1359
  • 相关阅读:
    Linux system basic 2 + add kernel for Jupyter
    Linux package installation: deb and rpm
    classification tips 01: npy file
    how to activate XMind8 to pro version.
    Linux system 初步
    try_except_finally
    Postgresql Json Sql
    python package install error and little code bugs
    小程序用户操作事件
    套数据操作步骤
  • 原文地址:https://www.cnblogs.com/cgmcoding/p/13298117.html
Copyright © 2011-2022 走看看