|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 游戏小虾米 于 2017-7-28 11:07 编辑
Tip:
一,理论
iter() #迭代器
next()
二,应用
1
>>> string = 'FishC'
>>> it = iter(string)
>>> next(it)
'F'
>>> next(it)
'i'
>>> next(it)
's'
>>> next(it)
'h'
>>> next(it)
'C'
>>> next(it)
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
next(it)
StopIteration
2 斐波纳契数列
>>> class 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
>>> fibs = Fibs()
>>> for each in fibs:
if each < 20:
print(each)
else:
break
1
1
2
3
5
8
13
3 数列另一种写法
>>> 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, self.b
>>> f = Fibs(100)
>>> for each in f:
print(each)
(1, 1)
(1, 2)
(2, 3)
(3, 5)
(5, 8)
(8, 13)
(13, 21)
(21, 34)
(34, 55)
(55, 89)
(89, 144)
三,课后练习 |
|