filter() 函数

mac2022-06-30  19

filter() 函数

描述

filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。

该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。

语法

以下是 filter() 方法的语法:

filter(function, iterable)

参数

function -- 判断函数。iterable -- 可迭代对象。

返回值

返回可迭代的对象。


实例

以下展示了使用 filter 函数的实例:

过滤出列表中的所有奇数:

1 #!/usr/bin/env python 2 # -*- encoding:utf-8 -*- 3 4 def is_odd(n): 5 """ 6 过滤出列表中的所有奇数: 7 :param n: 8 :return: 9 """ 10 return n % 2 == 1 11 12 13 newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) 14 # <filter object at 0x0000028702478A90> <class 'filter'> 15 print(newlist,type(newlist)) 16 for i in newlist: 17 print(i) 1 #!/usr/bin/env python 2 # -*- encoding:utf-8 -*- 3 4 newlist = filter(lambda n : n % 2 == 1, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) 5 # <filter object at 0x0000028702478A90> <class 'filter'> 6 print(newlist,type(newlist)) 7 for i in newlist: 8 print(i)

 

过滤出1~100中平方根是整数的数:

1 #!/usr/bin/env python 2 # -*- encoding:utf-8 -*- 3 4 import math 5 6 7 def is_sqr(x): 8 return math.sqrt(x) % 1 == 0 9 10 11 newlist = filter(is_sqr, range(1, 101)) 12 print(newlist) 13 for i in newlist: 14 print(i) 1 #!/usr/bin/env python 2 # -*- encoding:utf-8 -*- 3 import math 4 5 newlist = filter(lambda n : math.sqrt(n) % 1 == 0, range(1, 101)) 6 print(newlist) 7 for i in newlist: 8 print(i)

转载于:https://www.cnblogs.com/valorchang/p/11475813.html

最新回复(0)