zoukankan      html  css  js  c++  java
  • filter,map,reduce,lambda(python3)

    1.filter

    filter(function,sequence)

    对sequence中的item依次执行function(item),将执行的结果为True(符合函数判断)的item组成一个list、string、tuple(根据sequence类型决定)返回。

     1 #!/usr/bin/env python
     2 # encoding: utf-8
     3 """
     4 @author: 侠之大者kamil
     5 @file: filter.py
     6 @time: 2016/4/9 22:03
     7 """
     8 #filter map reduce lambda
     9 def f1(x):
    10     return x % 2 != 0 and x % 3 != 0
    11 a = filter(f1, range(2,25))
    12 print(a)#<filter object at 0x7f7ee44823c8>
    13 #这种情况是因为在3.3里面,filter()的返回值已经不再是list,而是iterators.
    14 print(list(a))
    15 def f2(x):
    16     return x != "a"
    17 print(list(filter(f2,"dfsafdrea")))

    结果:

    ssh://kamil@192.168.16.128:22/usr/bin/python3 -u /home/kamil/py22/jiqiao0406/fmrl.py
    <filter object at 0x7f4d1ca5e470>
    [5, 7, 11, 13, 17, 19, 23]
    ['d', 'f', 's', 'f', 'd', 'r', 'e']
    
    Process finished with exit code 0

    2.map

    语法与filter类似

     1 #!/usr/bin/env python
     2 # encoding: utf-8
     3 """
     4 @author: 侠之大者kamil
     5 @file: map.py
     6 @time: 2016/4/9 22:22
     7 """
     8 def cube(x):
     9     return x * x *x
    10 a = map(cube,range(10))
    11 print(list(a))
    12 def add(x,y,z):
    13     return x + y +z
    14 b = map(add,range(5),range(5),range(5))
    15 print(list(b))

     结果:

    ssh://kamil@192.168.16.128:22/usr/bin/python3 -u /home/kamil/py22/jiqiao0406/map.py
    [0, 1, 8, 27, 64, 125, 216, 343, 512, 729]
    [0, 3, 6, 9, 12]
    
    Process finished with exit code 0

    3.reduce

    reduce已经取消了,如想使用,可以用fuctools.reduce来调用。但是要先导入fuctools, 即输入:import fuctools 

    4.lambda

    快速定义最小单行函数

    1 g = lambda x:x *2
    2 print(g(5))
    3 print((lambda x:x *2)(5))

    结果:

    10
    10
    公众号请关注:侠之大者
  • 相关阅读:
    random、shutil、shevle、标准输入输出错误流
    Python中Json 和 pickle 详解
    Python 中的sys、os、os.path模块总结
    Python 中time,calendar,datatime模块总结
    包的概念和导入包的方法
    Python 中模块及其导入方式
    迭代器和生成器
    python 函数参数
    JAVA 配置Path环境变量
    腾讯云服务器简单配置web项目
  • 原文地址:https://www.cnblogs.com/kamil/p/5372909.html
Copyright © 2011-2022 走看看