如何找到“过滤器"的长度python中的对象 [英] How to find the length of a "filter" object in python
本文介绍了如何找到“过滤器"的长度python中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法得到我得到的列表的长度.所以我试着把它保存到一个变量中,就像这样......
<预><代码>>>>l = 过滤器(λ x:x>3,n)>>>长度(升)回溯(最近一次调用最后一次):文件<pyshell#5>",第 1 行,在 <module> 中长度(升)类型错误:过滤器"类型的对象没有 len()有没有什么办法可以得到这个长度,而不是使用循环?
解决方案
您必须以某种方式遍历过滤器对象.一种方法是将其转换为列表:
l = list(filter(lambda x: x > 3, n))len(l) # <--
但这首先可能会破坏使用 filter()
的意义,因为使用列表推导式可以更轻松地做到这一点:
l = [x for x in n if x >3]
同样,len(l)
将返回长度.
>>> n = [1,2,3,4]
>>> filter(lambda x:x>3,n)
<filter object at 0x0000000002FDBBA8>
>>> len(filter(lambda x:x>3,n))
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
len(filter(lambda x:x>3,n))
TypeError: object of type 'filter' has no len()
I could not get the length of the list I got. So I tried saving it to a variable, like this...
>>> l = filter(lambda x:x>3,n)
>>> len(l)
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
len(l)
TypeError: object of type 'filter' has no len()
Instead of using a loop, is there any way to get the length of this?
解决方案
You have to iterate through the filter object somehow. One way is to convert it to a list:
l = list(filter(lambda x: x > 3, n))
len(l) # <--
But that might defeat the point of using filter()
in the first place, since you could do this more easily with a list comprehension:
l = [x for x in n if x > 3]
Again, len(l)
will return the length.
这篇关于如何找到“过滤器"的长度python中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文