有时需要自定义一个迭代模式,如以0.5的步长迭代,或者只输出奇数项,反向迭代等
所谓的迭代器其实也是使用了next方法,所以,只要 合理利用next,就可以达到目的:
#!/usr/bin/env python #coding:utf-8 #@Author:Andy #Date: 2017/6/13 def frange(start, stop, step): """ Use yield to set a new iteration pattern such as float iterate you can set start=0, and the step you want """ x = start while x < stop: yield x x += step if __name__ == '__main__': for i in frange(0, 10, 0.5): print(i, end=' ') # 0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0 7.5 8.0 8.5 9.0 9.5 def impar_range(start, stop): """ yield impart index of a iterable """ i = start while i < stop: yield i i += 2 for i in impar_range(1, 20): print(i, end=' ') # 1 3 5 7 9 11 13 15 17 19 def count_down(n): """ count down from n to 0 """ i = n while 0 < i <= n: yield i i -= 1 for i in count_down(10): print(i, end = ' ') # 10 9 8 7 6 5 4 3 2 1