欢迎来到田晓东的博客

人生三从境界:昨夜西风凋碧树,独上高楼,望尽天涯路。 衣带渐宽终不悔,为伊消得人憔悴。 众里寻他千百度,蓦然回首,那人却在灯火阑珊处。
扩大
缩小

filter()函数

filter()函数是 Python 内置的另一个有用的高阶函数,filter()函数接收一个函数 f 和一个list,这个函数 f 的作用是对每个元素进行判断,返回 True或 False,filter()根据判断结果自动过滤掉不符合条件的元素,返回由符合条件元素组成的新list。

例如,要从一个list [1, 4, 6, 7, 9, 12, 17]中删除偶数,保留奇数,首先,要编写一个判断奇数的函数:

def is_odd(x):
    return x % 2 == 1

filter(is_odd, [1, 4, 6, 7, 9, 12, 17])
结果:
[1, 7, 9, 17]

利用filter()删除 None 或者空字符串:

def is_not_empty(s):
    return s and len(s.strip()) > 0
filter(is_not_empty, ['test', None, '', 'str', '  ', 'END'])
结果:

['test', 'str', 'END']

注意: s.strip(rm) 删除 s 字符串中开头、结尾处的 rm 序列的字符。

当rm为空时,默认删除空白符(包括'\n', '\r', '\t', ' '),如下:

a = ' 123'
a.strip()
结果:'123'

a = '\t\t123\r\n'
a.strip()
结果:'123'

用filter求素数

    #构造奇数序列
def _odd_iter():
    n = 1
    while True:
        n = n + 2
        yield n
#筛选函数
def _not_divisible(n):
    return lambda x: x % n > 0      #这句话的意思是if x%n>0 return x
#定义一个生成器
def primes():
    yield 2
    it =_odd_iter() #初始序列
    while True:
        n=next(it)  #返回序列的第一个数
        yield n
        it=filter(_not_divisible(n),it) #构造序列
# 打印1000以内的素数:
for n in primes():
    if n < 1000:
        print(n)
    else:
        break

posted on 2022-02-17 18:00  匍匐的仰望者  阅读(587)  评论(0编辑  收藏  举报

导航