Python builtin “all” with generators

后端 未结 5 866
太阳男子
太阳男子 2020-12-18 07:07

I have the following problem with python\'s \"all\" and generators:

G = (a for a in [0,1])
all(list(G))   # returns False - as I expected

B

5条回答
  •  忘掉有多难
    2020-12-18 07:58

    >>> G = (a for a in [0,1])
    >>> all(list(G))
    False
    >>> G = (a for a in [0,1])
    >>> all(G)
    False
    

    No True. However:

    >>> G = (a for a in [0,1])
    >>> all(list(G))
    False
    >>> all(G)
    True
    >>> all([])
    True
    

    If you call all a second time on the generator, you'll get True, as there are no False items left in the generator. As you can see, any empty sequence will work the same.

    For this particular example, all short-circuits, so you have 1 left to be generated after it returns False because of the leading 0 (if you don't use list) -- so it will return True the second time despite not being empty.

提交回复
热议问题