Return multiple values over time

后端 未结 2 1228
深忆病人
深忆病人 2020-12-21 10:13

Okay, so is there a way to return a value from a function - the way return does - but not stop the function - the way return does?

2条回答
  •  遥遥无期
    2020-12-21 11:07

    def f():
      for i in range(10):
         yield i
    
    g = f().next
    
    # this is if you actually want to get a function
    # and then call it repeatedly to get different values
    print g()
    print g()
    
    print
    
    # this is how you might normally use a generator
    for i in f():
      print i
    

    Output:

    0
    1
    
    0
    1
    ...
    9
    

提交回复
热议问题