Python: generator expression vs. yield

前端 未结 8 778
悲哀的现实
悲哀的现实 2020-12-07 08:43

In Python, is there any difference between creating a generator object through a generator expression versus using the yield statement?

8条回答
  •  情话喂你
    2020-12-07 09:07

    Using yield is nice if the expression is more complicated than just nested loops. Among other things you can return a special first or special last value. Consider:

    def Generator(x):
      for i in xrange(x):
        yield(i)
      yield(None)
    

提交回复
热议问题