Can generator be used more than once?

后端 未结 5 925
北荒
北荒 2021-02-13 06:53

This is my piece of code with two generators defined:

one_line_gen = (x for x in range(3))

def three_line_gen():
    yield 0
    yield 1
    yield 2
         


        
5条回答
  •  故里飘歌
    2021-02-13 07:49

    Why? I thought any generator can be used only once.

    Because every call to three_line_gen() creates a new generator.

    Otherwise, you're correct that generators only run forward until exhausted.

    Can generator be used more than once?

    Yes, it is possible if the results are buffered outside the generator. One easy way is to use itertools.tee():

    >>> from itertools import tee
    >>> def three_line_gen():
            yield 0
            yield 1
            yield 2
    
    >>> t1, t2 = tee(three_line_gen())
    >>> next(t1)
    0
    >>> next(t2)
    0
    >>> list(t1)
    [1, 2]
    >>> list(t2)
    [1, 2]
    

提交回复
热议问题