如何在python 3中找到过滤器对象的长度?
def is_valid_file(filename):
return True
full_path_fnames = filter(is_valid_file, full_path_fnames)
print(len(full_path_fnames))
答案 0 :(得分:11)
只有在完成迭代之后,你才可以说它有多少元素。内置len
函数调用对象的__len__
method,如您所见,filter
对象没有该方法
>>> '__len__' in dir(filter(bool, [0, 1, 2]))
False
因为它们基本上是迭代器。
找到长度的一种可能方法是
>>> sum(1 for _ in filter(bool, [0, 1, 2]))
2
另一个是将其转换为list
类型,当然有长度:
>>> len(list(filter(bool, [0, 1, 2])))
2
请注意,所有解决方案都会耗尽迭代器,因此您无法重复使用它:
>>> f = filter(bool, [0, 1, 2])
>>> list(f)
[1, 2]
>>> list(f)
[]
答案 1 :(得分:3)
在Python2.x中,filter
返回list
,但在Python3中,它为您提供了一个迭代器,您可以将其转换为list
,然后检查长度:
len(list(filter(foo, bar)))
演示:
>>> filter(lambda x: x < 3, [1,2,3])
<filter object at 0x7fdf9ea1af90>
>>> list(filter(lambda x: x < 3, [1,2,3]))
[1, 2]
>>> len(list(filter(lambda x: x < 3, [1,2,3])))
2