调用 filter 会返回 <filter object at ... > [英] Calling filter returns <filter object at ... >

查看:22
本文介绍了调用 filter 会返回 <filter object at ... >的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Python 中过滤器的概念.我正在运行这样一个简单的代码.

<预><代码>>>>def f(x): 返回 x % 2 != 0 和 x % 3 != 0>>>过滤器(f,范围(2, 25))

但我收到的不是列表,而是类似这样的消息.

<0x00FDC550 处的过滤器对象>

这是什么意思?这是否意味着我的过滤对象,即要出现的列表存储在该内存位置?我如何获得我需要的清单?

解决方案

看起来您正在使用 python 3.x.在python3中,filtermapzip等返回一个可迭代的对象,但不是一个列表.换句话说,

filter(func,data) #python 2.x

相当于:

list(filter(func,data)) #python 3.x

我认为它被改变是因为你(通常)想在懒惰的意义上进行过滤——你不需要消耗所有内存来预先创建一个列表,只要迭代器返回相同的列表在迭代过程中会发生的事情.

如果您熟悉列表推导式和生成器表达式,上面的过滤器现在(几乎)等价于 python3.x 中的以下内容:

( x for x in data if func(x) )

相反:

[ x for x in data if func(x) ]

在 python 2.x 中

I am learning the concept of filters in Python. I am running a simple code like this.

>>> def f(x): return x % 2 != 0 and x % 3 != 0
>>> filter(f, range(2, 25))

But instead of getting a list, I am getting some message like this.

<filter object at 0x00FDC550>

What does this mean? Does it means that my filtered object i.e list to come out is stored at that memory location? How do I get the list which I need?

解决方案

It looks like you're using python 3.x. In python3, filter, map, zip, etc return an object which is iterable, but not a list. In other words,

filter(func,data) #python 2.x

is equivalent to:

list(filter(func,data)) #python 3.x

I think it was changed because you (often) want to do the filtering in a lazy sense -- You don't need to consume all of the memory to create a list up front, as long as the iterator returns the same thing a list would during iteration.

If you're familiar with list comprehensions and generator expressions, the above filter is now (almost) equivalent to the following in python3.x:

( x for x in data if func(x) ) 

As opposed to:

[ x for x in data if func(x) ]

in python 2.x

这篇关于调用 filter 会返回 &lt;filter object at ... &gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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