如何找到“过滤器"的长度? python中的对象 [英] How to find the length of a "filter" object in python

查看:119
本文介绍了如何找到“过滤器"的长度? python中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

>>> 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)  # <--

但这可能首先会挫败使用filter()的意义,因为您可以通过列表理解更轻松地做到这一点:

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]

同样,len(l)将返回长度.

这篇关于如何找到“过滤器"的长度? python中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆