【问题标题】:Is there a reason for this behavior of the filter object in Python?Python中过滤器对象的这种行为是否有原因?
【发布时间】:2020-04-26 18:17:38
【问题描述】:
>>> a = filter(lambda x: x&1, [1,2])
>>> list(a)
[2]
>>> list(a)
[]

这很违反直觉,不是吗?因此,如果有人解释为什么会这样,请随意!

顺便说一下,我使用的是 Python 3.8.2

【问题讨论】:

    标签: python function filter behavior


    【解决方案1】:

    既然您知道用list() 包装对filter 的调用结果,我假设您熟悉生成器函数及其类似概念的概念。 filter 函数实际上返回类似于生成器函数的东西,因为它只能迭代一次。见下文:

    >>> a = filter(lambda x: x^1, [1,2])
    >>> type(a)
    <class 'filter'>
    >>> it = iter(a)
    >>> next(it)
    2
    >>> next(it)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    StopIteration
    >>> it = iter(a) # try to iterate the filter a second time
    >>> next(it) # you will get a StopIteration exception the very first time
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    StopIteration
    >>> 
    

    上面的代码本质上等价于:

    a = filter(lambda x: x^1, [1,2])
    print(type(a))
    for item in a:
        print(item)
    for item in a:
        print(item)
    

    【讨论】:

      【解决方案2】:

      a 是一个可迭代对象,其中的项目在您第一次调用 list(a) 时已被消耗。随后的 list(a) 将一无所获。

      同样,

      a = (i for i in range(10))
      list(a)
      [0, 1....10]
      list(a)
      []
      

      我更喜欢具有不同 IEnumerable 和 IEnumerator 接口的 C# 行为。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-01-05
        • 1970-01-01
        • 1970-01-01
        • 2019-10-19
        • 1970-01-01
        • 1970-01-01
        • 2020-05-05
        相关资源
        最近更新 更多