调用filter返回< filter对象位于...> [英] Calling filter returns <filter object at ... >

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

问题描述

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

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?

推荐答案

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

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

等效于:

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.

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

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

相对于:

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

在python 2.x中

in python 2.x

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

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