在Python3中的过滤器 [英] Filters in Python3

查看:164
本文介绍了在Python3中的过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Python中过滤器的概念。

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

但是,这样的消息。

 < 0x00FDC550的过滤器对象> 

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

解决方案

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

  filter(func,data)#python 2.x 


相当于:

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

我认为这是因为你以懒惰的方式进行过滤 - 只要迭代器返回列表在迭代过程中的相同内容,就不需要耗尽所有内存来预先创建列表。



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

 (x for data in func(x))

相对于:

  [x for data in func(x)] 

in 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

这篇关于在Python3中的过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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