首页 > 其他 > 详细

自定义迭代器:比如输入奇数项,反向迭代等

时间:2017-06-19 15:02:44      阅读:386      评论:0      收藏:0      [点我收藏+]

有时需要自定义一个迭代模式,如以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

 

自定义迭代器:比如输入奇数项,反向迭代等

原文:http://www.cnblogs.com/Andy963/p/7003254.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!