• python高阶函数—filter


    python内置了一个filter函数,用于过滤序列。和map函数类似,filter()函数也接受一个函数和一个序列。只不过filter函数中是把函数依次作用于序列中的每一个元素,如果是True则保留这个元素,如果是False,则舍弃这个元素。例如,给定一个list,删除偶数,保留奇数:

    >>> def is_odd(n):
    ...     return n % 2 ==1
    ...
    >>> list(filter(is_odd,[1,2,3,4,5,6]))
    [1, 3, 5]

    注意,filter返回的是一个Iterator,俗称惰性序列,所以要使用list()函数获得所有元素返回一个list。

    用filter求素数:

    素数的定义:又称质数,为大于1的自然数中,除了1和它本身以外不再有其他因数。

    计算素数的一个方法是埃氏筛法:

    首先从2开始的所有自然数中:

    2,3,4,5,6,7,8,9……

    取序列的第一个数2,他一定是素数,然后用2把序列的倍数去掉:

    3,5,7,9……

    去新序列的第一个数3,他一定是素数,然后用3 把序列的3的倍数去掉:

    5,7……:

    5一定是素数,然后用5把序列的5的倍数去掉:

    7,11……

    程序如下:

    >>> def odd_iter():#构造一个从3开始的奇数序列
    ...     n=1
    ...     while True:
    ...             n = n+2
    ...             yield n
    ...
    >>> def not_divisible(n):#筛选函数
    ...     return lambda x:x%n > 0
    ...
    >>> def primes(): #生成器,不断返回下一个素数
    ...     yield 2
    ...     it = odd_iter()#初始化序列
    ...     while True:
    ...             n = next(it)#取序列的第一个数
    ...             yield n
    ...             it = filter(not_divisible(n),it)#构造新序
    ...
    >>> for n in primes():
    ...     if n < 1000:
    ...             print(n)
    ...     else:
    ...             break
    ...

    结果:

    2
    3
    5
    7
    11
    13
    17
    19
    23
    ……
    953
    967
    971
    977
    983
    991
    997

    练习:

    利用filter函数筛选出1~1000中的回数(回数是指从左往右和从右到左读都一样的数,例如1221,676):

    >>> def is_palindrome(n):
    ...     return n == int(str(n)[::-1])
    ...
    >>> list(filter(is_palindrome,range(1,1000)))
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88,
    ……
    39, 949, 959, 969, 979, 989, 999]
  • 相关阅读:
    The lexer hack
    How Clang handles the type / variable name ambiguity of C/C++
    python
    基于asp.net + easyui框架,一步步学习easyui-datagrid——界面(一)
    程序员最该看的30本书---------------------------国外编辑推荐
    DirectX 学习经典参考书籍 电子书下载
    基于asp.net+ easyui框架,js提交图片,实现先上传图片再提交表单
    请问JAVA三层架构,持久层,业务层,表现层,都该怎么理解?和MVC三层模型有什么区别
    对java框架的几点认识
    J2EE入门必备
  • 原文地址:https://www.cnblogs.com/hiwuchong/p/8094924.html
Copyright © 2020-2023  润新知