for 语句就是触发这个迭代器的功能呢
for i in "chenshiba":
print(i)
--------------------------
c
h
e
n
s
h
i
b
a
字典_迭代
linsk ={"name": "张三", "age":20, "sex":"男", "color":"red"}
for each in linsk:
print("%s ---> %s" % (each, linsk[each]))
-------------------
name ---> 张三
age ---> 20
sex ---> 男
color ---> red
iter() next()迭代器
string = "chenshiba"
ti = iter(string)
print(next(ti))
print(next(ti))
print(next(ti))
print(next(ti))
------------------- # 不会在往下执行,, 如果后面没有了数据就会提示报错 StopIteration
c
h
e
n
while True:
try:
print(next(ti))
except:
break
while True:
try:
print(next(ti))
except StopIteration:
break
-------------------
c
h
e
n
s
h
i
b
a
-iter() -__iter()表示魔法方法的迭代器
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
f1 = Fibs()
for each in f1:
if each <= 20:
print(each)
else:
break
-----------------------------
1
1
2
3
5
8
13
升级版 , 可自定义参数
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
f1 = Fibs(100)
for each in f1:
print(each)
-------------------------
1
1
2
3
5
8
13
21
34
55
89