网络编程
位置:首页>> 网络编程>> Python编程>> Python filter过滤器原理及实例应用

Python filter过滤器原理及实例应用

作者:深藏blueblueblue  发布时间:2021-03-20 13:11:13 

标签:Python,filter,过滤器

filter的语法:filter(函数名字,可迭代的变量)

其实filter就是一个“过滤器”:把【可迭代的变量】中的值,挨个地传给函数进行处理,那些使得函数的返回值为True的变量组成的迭代器对象就是filter表达式的结果

那filter的第一个参数,即函数的返回的值必须是bool类型,第二个参数必须是可迭代的变量:字符串、字典、元组、集合

其实从源码中也能大概看出filter是个什么东西

Python filter过滤器原理及实例应用

下面来看一些实际的代码示例:

打印列表中以“A”开头的名字


def first_name(x):
 if x.startswith("A"):
   return True
 else:
   return False
name = ["Alex","Hana","Anny","Sunny"]
f = filter(first_name, name)
a_name = list(f)
print("f:",f)
print("a_name:",a_name)

输出结果为:

f: <filter object at 0x10cb28700>
a_name: ['Alex', 'Anny']

下面再来一个filter和lambda结合的例子:

打印人员信息的字典中,年纪大于18的人


people = [
 {"name":"Alex","age":20},
 {"name":"Hana","age":19},
 {"name":"Anny","age":16},
 {"name":"Sunny","age":18},
]
f = filter(lambda p:p["age"]>18, people)
print(list(f))

输出结果为:

[{'name': 'Alex', 'age': 20}, {'name': 'Hana', 'age': 19}]

第二个参数也可以是字符串:

qq_mail = "123@qq.com"
f = filter(lambda m:m.isnumeric(),qq_mail)
print(list(f))

输出结果:

['1', '2', '3']

来源:https://www.cnblogs.com/lybolg/p/12520208.html

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com