python filter函数
描述:
filter()函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。
接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判断,返回True或False,将返回True的元素放到新列表中。
语法:
filter(function, iterable)
参数:
function:判断函数
iterable:可迭代对象
返回值:
列表
求偶数
lst=[1,2,3,4,5,6,7]
newlst=filter(lambda x:x%2==0,lst)
print(list(newlst))
判断1..100开根号是否为整数
import math
'''
lst=[1,2,3,4,5,6,7]
print(list(map(lambda x:x%2,lst)))
newlst=filter(lambda x:x%2==0,lst)
print(list(newlst))
'''
Inlst=filter(lambda x:math.sqrt(x)%1==0,range(1,101))
print(list(Inlst))
结果
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
filter的func携带额外参数
data = [
{'name': 'jim', 'money': 133, 'home': 'ame'},
{'name': 'tom', 'money': 456, 'home': 'chin'}
]
def func(v, a):
if v.get('name') == a:
return True
return False
res = filter(lambda x: func(x, 'tom'), data)