zoukankan      html  css  js  c++  java
  • 函数式编程--高阶函数--filter

    定义

    Python内置的filter函数用于过滤序列。

    filter(functioniterable)

    filter接受一个函数和一个可迭代对象,将函数作用于iterable的每一个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。

    注意到filter()函数返回的是一个Iterator,也就是一个惰性序列,所以要强迫filter()完成计算结果,需要用list()函数获得所有结果并返回list。

    示例

    #在一个list中,删掉偶数,只保留奇数
    
    L= [1,2,3,4,6,7,10,13,14]
    
    def  is_odd(n):
        return  n%2==1
    
    print(list(filter(is_odd,L)))

    字符串strip的用法: http://www.runoob.com/python/att-string-strip.html

    #把一个序列的空字符串删掉
    
    L=['A', '', 'B', None, 'C', '  ']
    
    def not_empty(s):
        return s and s.strip()
    
    print(list(filter(not_empty,L)))

    python lambda用法:http://www.cnblogs.com/evening/archive/2012/03/29/2423554.html

    #定义一个素数序列
    #1.定义一个以3开始的所有奇数序列
    def is_odd():
        n=1
        while True:
            n=n+2
            yield n
    
    #定义一个排除其他数的函数,所有可整数的数字都不是素数
    def  _not_divisible(n):
        return  lambda  x:x%n > 0
    
    #定义一个生成器,生成素数序列
    def  primes():
        #输出素数2
        yield 2
        it =is_odd()
        while  True:
            #输出素数3
            n=next(it)
            yield n
            #filter作用于it的每一个元素
            it=filter(_not_divisible,it)
    
    #输出100以内的素数
    for n in primes():
        if n <100:
            print(n)
        else:
            break

    练习题答案:http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014317799226173f45ce40636141b6abc8424e12b5fb27000

    #输出1000以内的回数
    def  is_palindrome(n):
        strn=str(n)
        strf = strn[::-1]
        if strn==strf:
            return True
        else:
            return False
     
    output=filter(is_palindrome,range(1,1000))
    print(list(output)) 
  • 相关阅读:
    大数据问题集锦
    分析JMeter聚合报告中的各项指标
    Jmeter之正则表达式提取器应用
    mysql忘记密码怎么办?
    ARIMA模型
    ADF检验
    第13章 时间序列分析和预测
    pandas的基本功能
    pandas库
    PS常用快捷键
  • 原文地址:https://www.cnblogs.com/wangxy92/p/6769358.html
Copyright © 2011-2022 走看看