Can generator be used more than once?

后端 未结 3 990
遇见更好的自我
遇见更好的自我 2021-02-13 07:18

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
         


        
3条回答
  •  囚心锁ツ
    2021-02-13 07:59

    no, you can not iterate over a generator twice. a generator is exhausted once you have iterated over it. you may make a copy of a generator with tee though:

    from itertools import tee
    
    one_line_gen = (x for x in range(3))
    gen1, gen2 = tee(one_line_gen)
    # or: 
    # gen1, gen2 = tee(x for x in range(3))
    
    for item in gen1:
        print(item)
    
    for item in gen2:
        print(item)
    

    for the other issues see Ofer Sadan's answer.

提交回复
热议问题