目录
一、描述
语法
返回值
二、实例
1.过滤出列表中的所有奇数
2.过滤出1~100中平方根是整数的数:
一、描述
英文文档
filter
(function, iterable)
Construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None
, the identity function is assumed, that is, all elements of iterable that are false are removed.
Note that filter(function, iterable)
is equivalent to the generator expression (item for item in iterable iffunction(item))
if function is not None
and (item for item in iterable if item)
if function is None
.
See for the complementary function that returns elements of iterable for which functionreturns false.
filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,如果要转换为列表,可以使用 list() 来转换。
该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判断,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。
语法
filter(function, iterable)
- function -- 判断函数。
- iterable -- 可迭代对象。
返回值
返回一个迭代器对象(不是原有数据类型,需转换格式)
二、实例
1.过滤出列表中的所有奇数
#!/usr/bin/python3
def is_odd(n):
return n % 2 == 1
tmplist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
newlist = list(tmplist)
print(newlist)
输出结果 :[1, 3, 5, 7, 9]
结合前面学到的Lambda表达式,可以使用函数式编程来实现
#!/usr/bin/python3
tmplist = filter(lambda x:x%2, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
newlist = list(tmplist)
print(newlist)
2.过滤出1~100中平方根是整数的数:
#!/usr/bin/python3
import math
def is_sqr(x):
return math.sqrt(x) % 1 == 0
tmplist = filter(is_sqr, range(1, 101))
newlist = list(tmplist)
print(newlist)
输出结果 :[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]