filter:过滤,过滤器
根据字面意思就是过滤,或筛选匹配的东西
先看需求;有一组list,需要筛选出某个条件的元素,组成新的list。没学filter肯定用for循环。
直接for循环
list_a=['sb_alex_nb','sb_wupeiqi','linhaifeng_nb','sb_yuanhao']
list_b=[]
for i in list_a:
# if "sb" not in i:
if not i.startswith('sb'):
list_b.append(i)
print(list_b)
增加功能,可选择筛选sb开头的,或者nb结尾的
list_a = ['sb_alex_nb', 'sb_wupeiqi', 'linhaifeng_nb', 'sb_yuanhao']
def sb_check(i):
return i.startswith('sb')
def nb_check(i):
return i.endswith('nb')
def test(func, array):
list_b = []
for i in array:
if func(i):
list_b.append(i)
return list_b
res_1 = test(sb_check, list_a)
res_2 = test(nb_check, list_a)
print(res_1)
print(res_2)
这其实完成的就是filter函数的功能,对iterable的元素for循环进行func查找,筛选满足条件的
filter格式:filter(func,interable)
list_a = ['sb_alex_nb', 'sb_wupeiqi', 'linhaifeng_nb', 'sb_yuanhao']
res = filter(lambda x: x.startswith('sb'), list_a)
print(res)
print(list(res))
元素为字典的筛选
people=[
{"name":"lhf","age":1000},
{"name":"wpq","age":900},
{"name":"sb","age":18}
]
res=filter(lambda x:x["age"]<20,people)
print(list(res))