filter函数的返回值是什么【filter函数用法实例】

748次阅读
没有评论
filter函数的返回值是什么【filter函数用法实例】

python filter函数的返回值是什么

filter函数说明

filter()函数被用于过滤序列,它会过滤掉不符合条件的数据,符合条件的数据将会被留下,filter函数返回的结果是一个可迭代对象。

之所以称它为高级语法,因为想要正确理解使用它并不容易,同时还要配合上lambda表达式。

filter函数语法

filter(function, iterable)

filter函数参数

function — 判断函数。

iterable — 可迭代对象。

filter函数返回值

返回列表。

filter函数实例

from collections import Iterable
 
def func(x):
    print("接收参数" + str(x))
    return x%2 == 0
 
lst = [1, 2, 5, 6, 7]
res = filter(func, lst)
# res 是一个可迭代对象
print(isinstance(res, Iterable), type(res))
 
for item in res:
print(item)

filter函数的返回值是一个可迭代对象,这一点很关键,这也是为什么我说filter函数是高级语法的原因。

为什么不返回列表?,如果返回的是列表,那么在filter函数执行过程中,就必须对列表里的每一个数据进行对2取模运算,这样很浪费空间,因此filter在实现时采用了迭代器技术,将计算延迟到对filter函数返回结果进行遍历时才进行。

通过本篇的学习,我们发现了filter函数的返回值,同时掌握了过滤序列数据的方法,学会的赶紧也动手试试吧。

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-05-13发表,共计684字。
新手QQ群:570568346,欢迎进群讨论 Python51学习