马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
支持迭代操作:字符串,字典,文件
iter()
next()>>> it = iter("FishC")
>>> next(it)
'F'
>>> next(it)
'i'
>>> next(it)
's'
魔法方法__iter__()
__next__() # 决定了迭代器的规则
练习1class Fibs:
def __init__(self):
self.a = 0
self.b = 1
def __iter__(self):
# 本身就是迭代器,返回本身即可
return self
def __next__(self):
self.a, self.b = self.b, self.a + self.b # 一一对应
return self.a
但是他是没有终止的,会不断地运行。
方法1:设置循环上限fibs = Fibs()
for each in fibs:
if each < 20:
print(each)
else:
break
方法2:参数设置class Fibs:
def __init__(self, n = 20): # 可在这里简易调整
self.a = 0
self.b = 1
self.n = n
def __iter__(self):
return self
def __next__(self):
self.a, self.b = self.b, self.a + self.b
if self.a > self.n:
raise StopIteration
return self.a
注:若当前位置无元素,则抛出 StopIteration异常。
动动手:
0. 用while 实现以下内容for each in range(5):
print(each)
alist = range(5)
it = iter(alist)
while True:
try:
print(next(it))
except StopIteration:
break
1. 写一个迭代器,输出所有至今为止的闰年,效果如下>>> leapYears = LeapYear()
>>> for i in leapYears:
if i >=2000:
print(i)
else:
break
2012
2008
2004
2000
参考代码import datetime as dt
class LeapYear:
def __init__(self):
self.now = dt.date.today().year
def isLeapYear(self, year):
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
return True
else:
return False
def __iter__(self):
return self
def __next__(self):
# 不是闰年
while not self.isLeapYear(self.now):
self.now -= 1
temp = self.now
self.now -= 1
return temp
2. 写一个MyRev类,功能 = reversed(),例如:>>> myRev = MyRev("FishC")
>>> for i in myRev:
print(i, end='')
ChsiF
参考代码:class MyRev:
def __init__(self, data):
self.data = data
self.index = len(data)
def __iter__(self):
return self
def __next__(self):
if self.index == 0:
raise StopIteration
self.index -= 1
return self.data[self.index]
myRev = MyRev('FishC')
for i in myRev:
print(i, end = '')
|