python 用yield创建新的迭代模式

分享
程序员 2024-9-16 07:02:56 92 0 来自 中国
4.3 我们想实现一个自定义的迭代模式,来区别常见的内建函数range reversed函数等


  • 可以利用生成器函数,来实现一种新的迭代
>>> def frange(start,stop,increment):...      x = start...      while x < stop:...          yield x...          x+=increment>>> for n in frange(0,4,0.5):...     print(n)...00.51.01.52.02.53.03.5>>> list(frange(0,1,0.125))[0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]>>>

  • 函数中只要出现了yield函数,就会酿成一个生成器,与平常函数差别,生成器只有再相应了迭代操纵时才运行,下面研究下他的机制
>>> def c(n):...     print('starting to count form',n)...     while n >0:...         yield n...         n -=1...     print('done')...>>> c =c(3)>>> c<generator object c at 0x104beff50>>>> next(c)starting to count form 33>>> next(c)2>>> next(c)1>>> next(c)doneTraceback (most recent call last):  File "<stdin>", line 1, in <module>StopIteration>>>

  • 这里函数的核心特性就是,在相应了迭代过程的next时才会运行,一旦生成器的函数返回,迭代也就制止了。
  • 但是通常环境下for自带就处置惩罚了这些过程,不消再单独处置惩罚竣事的返回
您需要登录后才可以回帖 登录 | 立即注册

Powered by CangBaoKu v1.0 小黑屋藏宝库It社区( 冀ICP备14008649号 )

GMT+8, 2024-10-19 04:31, Processed in 0.194982 second(s), 32 queries.© 2003-2025 cbk Team.

快速回复 返回顶部 返回列表