python中yield的理解基础方法

[python] 2024-04-28 圈点291

摘要:python中yield比较难理解,这个示例可以很方便的理解方法

对yield的基础理解方法,如下:

示例:

def test( data_list ):

            for x in data_list:

                 yield x + 1

      data = [1,2,3,4]

      for y in test( data ):

           print y


结果: 2 3 4 5


另一种手动方法:

handle = test(data)

handle.next()     输出  2

handle.next()     输出  3
handle.next()     输出  4
handle.next()     输出  5
handle.next()    报错


yield  

感谢反馈,已提交成功,审核后即会显示