zoukankan      html  css  js  c++  java
  • Python的map,reduce,filter函数

    #数据准备
    List1=range(10)
    list(List1)
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
     
    map函数
    可以操作可迭代对象,输出也是可迭代的对象
    def f_map(x):
        return x**2
    #使用map函数
    List2=map(f_map,List1)
    list(List2)
    [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
    #使用lambda表达式实现map
    List3=map(lambda x:x**2,List1)
    list(List3)
    [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
     
    reduce函数
    可以操作一组可迭代的对象,得到一个数值
    from functools import reduce
    def f_reduce1(x,y):
        return x+y
    def f_reduce2(x,y):
        return x*10+ y
    #把一组list变成十进制的数
    #使用reduce函数
    List4=reduce(f_reduce1,List1)
    print(List4)
    List5=reduce(f_reduce2,List1)
    print(List5)
    45
    123456789
    #使用lambda表达式实现reduce
    List6=reduce(lambda x,y:x+y,List1)
    print(List6)
    List7=reduce(lambda x,y:x*10+y,List1)
    print(List7)
    45
    123456789
     
    filter函数
    #第一个例子,过滤出奇数
    def is_odd(x):
        return x%2==1
    List8=filter(is_odd,List1)
    print(list(List8) )
    #第二个例子:过滤出平方根是整数的数
    import math
    def is_squr(x):
        return math.sqrt(x)%1==0
    List9=filter(is_squr,range(1,101))
    print(list(List9))
    #使用lambda表达式实现了filter
    List10=filter(lambda x:math.sqrt(x)%1==0,range(1,101))
    print(list(List10))
    [1, 3, 5, 7, 9]
    [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
    [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
     

    <wiz_tmp_tag id="wiz-table-range-border" contenteditable="false" style="display: none;">






    万事走心 精益求美


  • 相关阅读:
    nohup 命令的使用
    Linux下完全删除用户
    free命令详解
    Nginx页面不能访问排查思路
    netstat命令详解
    VMware Workstation工具给liunx创建共享磁盘
    yum命令使用小技巧
    Linux 常用命令-- top
    ssh免密访问对端服务
    Java根据IP获取地区(淘宝接口)
  • 原文地址:https://www.cnblogs.com/kongchung/p/9106328.html
Copyright © 2011-2022 走看看