zoukankan      html  css  js  c++  java
  • python3高阶函数:map(),reduce(),filter()的区别

    转载请注明出处:https://www.cnblogs.com/shapeL/p/9057152.html

    1.map():遍历序列,对序列中每个元素进行操作,最终获取新的序列

    1 print(list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9])))
    输出结果:
    ['1', '2', '3', '4', '5', '6', '7', '8', '9']
    1 def square(x):
    2     return x**2
    3 result = list(map(square,[1,2,3,4,5]))
    4 print(result)
    输出结果:
    [1, 4, 9, 16, 25]

    备注:map()执行后发现返回结果:<map object at 0x006F34F0>

    因为map():Python 2.x 返回列表;Python 3.x 返回迭代器

    1 def square(x):
    2     return x**2
    3 result = map(square,[1,2,3,4,5])
    4 print(result)
    输出结果:
    <map object at 0x006F34F0>
    在python3里面,map()的返回值已经不再是list,而是iterators, 所以想要使用,只用将iterator转换成list即可, 比如list(map())


    2.reduce():对于序列内所有元素进行累计操作,即是序列中后面的元素与前面的元素做累积计算(结果是所有元素共同作用的结果)
    1 def square(x,y):
    2      return x*y
    3 result = reduce(square,range(1,5))
    4 print(result)
    输出结果:
    24

     

    3.filter():‘筛选函数’,filter()把传人的函数依次作用于序列的每个元素,然后根据返回值是True还是false决定保留还是丢弃该元素,返回符合条件的序列

    1 def func(x):
    2     return x%2==0
    3 print(list(filter(func,range(1,6))))
    输出结果:
    [2, 4]

     



  • 相关阅读:
    Java实现 LeetCode 461 汉明距离
    在Linux运行期间升级Linux系统(Uboot+kernel+Rootfs)
    AM335x(TQ335x)学习笔记——挂载Ramdisk
    Ramdisk文件系统的制作与调试运行
    u-boot向linux内核传递启动参数(详细)
    uboot环境变量与内核MTD分区关系
    MMU
    INTERRUPT CONTROLLER
    UART
    GPIO
  • 原文地址:https://www.cnblogs.com/shapeL/p/9057152.html
Copyright © 2011-2022 走看看