Can generator be used more than once?

后端 未结 5 808
北荒
北荒 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:46

    Because in One liner is Generator Object while the three liner is a function. They meant to be different.

    These two are similar.

    def three_line_gen_fun():
        yield 0
        yield 1
        yield 2
    
    three_line_gen = three_line_gen_fun()
    one_line_gen = (x for x in range(3))
    
    type(three_line_gen) == type(one_line_gen)
    

提交回复
热议问题