Yield multiple values

前端 未结 3 436
长发绾君心
长发绾君心 2021-01-30 20:56

Can\'t we yield more than one value in the python generator functions?

Example,

In [677]: def gen():
   .....:     for i in range(5):
   .....:         y         


        
3条回答
  •  梦毁少年i
    2021-01-30 21:14

    Use yield from

    def gen():
        for i in range(5):
            yield from (i, i+1)
    
    [v for v in gen()]
    # [0, 1, 1, 2, 2, 3, 3, 4, 4, 5]
    

    The python docs say:

    When yield from is used, it treats the supplied expression as a subiterator.

提交回复
热议问题