函数式编程--高阶函数--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)) 

 

转载于:https://www.cnblogs.com/wangxy92/p/6769358.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值