Yield multiple values

前端 未结 3 437
长发绾君心
长发绾君心 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条回答
  •  清歌不尽
    2021-01-30 21:23

    Your function gen returns a generator and not values as you might expect judging from the example you gave. If you iterate over the generator the pairs of values will be yielded:

    In [2]: def gen():
       ...:     for i in range(5):
       ...:         yield i, i+1
       ...:         
    
    In [3]: for k1, k2 in gen():
       ...:     print k1, k2
       ...:     
    0 1
    1 2
    2 3
    3 4
    4 5
    

提交回复
热议问题