Python 3.x: Test if generator has elements remaining

后端 未结 4 1215
旧巷少年郎
旧巷少年郎 2021-02-04 00:56

When I use a generator in a for loop, it seems to \"know\", when there are no more elements yielded. Now, I have to use a generator WITHOUT a for loop, and use next

4条回答
  •  感情败类
    2021-02-04 01:38

    The two statements you wrote deal with finding the end of the generator in exactly the same way. The for-loop simply calls .next() until the StopIteration exception is raised and then it terminates.

    http://docs.python.org/tutorial/classes.html#iterators

    As such I don't think waiting for the StopIteration exception is a 'heavy' way to deal with the problem, it's the way that generators are designed to be used.

提交回复
热议问题