Python builtin “all” with generators

后端 未结 5 841
太阳男子
太阳男子 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 08:11

    No, it doesn't. The following snippet returns False

    G = (a for a in [0,1])
    all(G)         # returns False
    

    Are you perhaps doing the following

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

    In that case, you are exhausting the generator G when you construct the list, so the final call to all(G) is over an empty generator and hence returns the equivalent of all([]) -> True.

    A generator can't be used more than once.

提交回复
热议问题