【问题标题】:Has `filter()` changed between Python 2.x and 3.x?`filter()` 在 Python 2.x 和 3.x 之间是否发生了变化?
【发布时间】:2014-07-18 06:46:00
【问题描述】:

我为filter() 使用匿名函数尝试了许多不同的示例,但只要我在字符串上使用它,总是会得到奇怪的结果。下面是一个例子:

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

如果不是字符串,一切正常。例如;

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

顺便说一下,如果我去掉list()函数部分,就会出现类似字符串大小写的问题:

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

我在 Windows 7 上使用 Python 3.4.1。

【问题讨论】:

  • 一句话:yes.

标签: python string filter anonymous-function


【解决方案1】:

是的。在 3.x 中,一些功能工具(最值得注意的是 filter()map())已更改为返回迭代器而不是序列。

【讨论】:

    【解决方案2】:

    在 Python 2 中,filter() 函数返回一个列表,该列表是通过一个函数过滤序列的结果,该函数为序列中的每个项目返回 True 或 False。在 Python 3 中,filter() 函数返回一个迭代器,而不是一个列表。 来源:diveintopython3.net

    2to3 tool 在某些情况下会在对 filter() 的调用周围放置一个 list() 调用,以确保结果仍然是一个列表。如果您需要在没有 2to3 转换的情况下在 Python 2 和 Python 3 中运行的代码,并且您需要结果是一个列表,您也可以这样做。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-01
      • 2012-10-27
      • 1970-01-01
      • 2015-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多