python函数式编程-filter

  • filter用法

    1. filter(f,iterator),返回由符合条件元素组成的新列表
    2. filter和map类似,根据每个值是True还是False决定是否保留元素
    3. filter返回的也是惰性序列,由于使用惰性计算,只有取filter结果的时候,才会每次真正筛选并返回筛选的元素.
  • example 1: 判断奇偶

    1
    2
    3
    4
    def is_odd(x):
    return x%2 == 0
    ans = list(filter(is_odd,[1,2,3,4,5,6,7,8,9]))
    print(ans)
    1
    [2, 4, 6, 8]
  • example 2: 删除空字符

    1
    2
    3
    4
    def not_empty(x):
    return x and x.strip()
    ans = list(filter(not_empty,['a',' ','b',' ']))
    print(ans)
    1
    ['a', 'b']
  • example 3: 欧几里得算法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
     def _not_visible(n):
    return lambda x:x%n>0
    #返回的是一个匿名函数
    #比如_not_visible(3)返回函数lambda x:x%3>0,调用lambda x:x%3>0这个函数时传入x
    def _odd_filter():
    n = 1
    while True:
    n = n+2
    yield n#yield节省内存空间
    def primes():
    yield 2
    it = _odd_filter()
    while True:
    n = next(it)
    yield n#获取序列的第一个数
    it = filter(_not_visible(n),it)#每个元素对n进行%判断,留下质数作为新序列
    for n in primes():
    if n < 100:
    print(n,end=' ')
    else:
    break
    print()#换行
    1
    2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
  • test : 判断200以内回文数
    思路:转为字符串,判断回文串

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    def is_palidrome(n):
    a = str(n)
    start = 0;end = len(a)-1
    while start < end:
    if(a[start] != a[end]):
    return False
    start,end = start+1,end-1;
    return True
    ans = list(filter(is_palidrome,range(1,200)))
    print(ans)
    1
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191]

参考:
Python filter函数
高阶函数filter