Python filter()函数

Python filter()函数


filter()函数顾名思义,就是过滤器,它是Python内置的高级函数之一。

filter()函数接收2个参数,一个是用来筛选的谓词函数(即返回值是True或者False的函数)和一个序列。filter()函数将使用谓词函数对所有序列中的元素进行处理,保留其中返回值是True的元素,以filter类型的对象保存。

格式:

filter(function, iterable)

用法示例:

#!usr/bin/env python3
#_*_ coding: utf-8 _*_
def isodd(n):
    return (n%2) == 1
r = filter(isodd, range(1,6))
print(r)
print(list(r))

#结果
<filter object at 0x03902190>
[1, 3, 5]

用filter求素数:
https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431821084171d2e0f22e7cc24305ae03aa0214d0ef29000

原文地址:https://www.cnblogs.com/wanghongze95/p/13842613.html