python内置高阶函数之:filter函数

filter函数包含两个参数
1.condition_function
这个参数是一个用来说明过滤条件的函数,他的返回值往往是一个用来判断是否保留的布尔型变量。
2.iterable_to_filter
这个参数是用来指定需要过滤的迭代器
3.filter函数的输出也是一个迭代器

我们自己编写一个自定义的filter_sefl函数,然后使用实例与系统内置的filter函数进行比较,具体的代码如下:

class Student():
	def __init__(self,name,sex,height):
		self.name = name
		self.sex = sex
		self.height = height

def height_condition(stu):
	if stu.sex == 'male':
		return stu.height > 1.75
	else:
		return stu.height > 1.65

students = [
	Student('xiaoming','male',1.74),
	Student('xiaohong','female',1.68),
	Student('xiaoli','male',1.80)
]

def filter_self(function,iterable):	#迭代器
	return iter([ item for item in iterable if function(item)])
print("###################Use the customized 'filter_self' funcion#######################")
students_satisfy = filter_self(height_condition,students)
for stu in students_satisfy:
	print(stu.name)
print("###################Use the inner 'filter' funcion#######################")
students_satisfy = filter(height_condition,students)
for stu in students_satisfy:
	print(stu.name)

运行结果如下:

###################Use the customized 'filter_self' funcion#######################
xiaohong
xiaoli
###################Use the inner 'filter' funcion#######################
xiaohong
xiaoli
[Finished in 0.7s]

我们可以看到,两者获得了相同的结果。

发布了207 篇原创文章 · 获赞 16 · 访问量 9871

猜你喜欢

转载自blog.csdn.net/weixin_41855010/article/details/104692652