最近在学习python的itertools模块,发现该模块有一个ifilter方法,原型如下:
itertools.ifilter(predicate, iterable)
该方法乍一看与内置函数filter:
filter(function, iterable)
非常类似,但是两者是决然不同的,以下官方文档对filter的介绍,其中提到了这两个函数:
Filter construct a list from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator.
If iterable is a string or a tuple, the result also has that type; otherwise it is always a list.
If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.
Note that filter(function, iterable) is equivalent to[item for item in iterable if function(item)]
if function is not None and[item for item in iterable if item]
if function is None.
See itertools.ifilter() and itertools.ifilterfalse() for iterator versions of this function, including a variation that filters for elements where the function returns false.
filter函数的返回值是list或string,他其实相当于一个列表生成式,ifilter是filter的迭代器版本,它的返回值是一个iterator。
这就引出了一个问题,一个函数返回list和返回iterator有什么差异,以及各自的使用场合是什么?
经过我的测试,我发现:
list(itertools.ifilter(predicate, iterable))
与
filter(predicate, iterable)
是等价的。