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
    公众号请关注:侠之大者
  • 相关阅读:
    让.Net程序支持命令行启动
    拒绝卡顿——在WPF中使用多线程更新UI
    比NPOI更好用的Excel操作库——EPPlus
    利用Visual Studio Natvis 框架简化C++的变量调试工作
    使用LibZ合并.Net程序集,支持WPF
    SONY新的圈铁耳机
    找回VisualStudio异常设置中丢失的“用户未处理的(User-unhandled)”列
    去除下载文件属性中烦人的锁定状态
    POJ 3347 Kadj Squares
    POJ 1696 Space Ant(极角排序)
  • 原文地址:https://www.cnblogs.com/kamil/p/5372909.html
Copyright © 2011-2022 走看看