简体   繁体   English

`filter()` 在 Python 2.x 和 3.x 之间是否发生了变化?

[英]Has `filter()` changed between Python 2.x and 3.x?

I tried many different examples for filter() with anonymous functions, but always get strange results as long as I use it on strings.我用匿名函数尝试了许多不同的filter()示例,但只要我在字符串上使用它,总是会得到奇怪的结果。 Below is an example:下面是一个例子:

>>>print(filter(lambda x: x.isdigit(), "aas30dsa20"))
<filter object at 0x00000000035DE470>

If not strings, everything works fine.如果不是字符串,一切正常。 Eg;例如;

>>> print(list(filter(lambda x: x >= 30 and x <= 70, [x**2 for x in range(1,11)])))
[36, 49, 64]

By the way, if I remove the list() function part, the problem similar to string case appears:顺便说一句,如果我删除list()函数部分,就会出现类似于字符串大小写的问题:

>>> print(filter(lambda x: x >= 30 and x <= 70, [x**2 for x in range(1,11)]))
<filter object at 0x00000000037BFDD8>

I am using Python 3.4.1 on Windows 7.我在 Windows 7 上使用 Python 3.4.1。

Yes.是的。 Several functional tools (most notably filter() and map() ) were changed to return iterators instead of sequences for 3.x.几个功能性工具(最显着的是filter()map() )被更改为返回迭代器而不是 3.x 的序列。

In Python 2, the filter() function returned a list, the result of filtering a sequence through a function that returned True or False for each item in the sequence.在 Python 2 中,filter() 函数返回一个列表,这是通过一个函数过滤序列的结果,该函数为序列中的每个项目返回 True 或 False。 In Python 3, the filter() function returns an iterator, not a list.在 Python 3 中,filter() 函数返回一个迭代器,而不是一个列表。 Source: diveintopython3.net资料来源: diveintopython3.net

2to3 tool will in some cases place a list() call around the call to filter() to ensure that the result is still a list. 2to3 工具在某些情况下会在对 filter() 的调用周围放置一个 list() 调用,以确保结果仍然是一个列表。 If you need code that runs in both Python 2 and Python 3 without 2to3 conversion and you need the result to be a list, you can do the same.如果您需要在没有 2to3 转换的情况下在 Python 2 和 Python 3 中运行的代码,并且您需要结果是一个列表,您可以这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM