1. for 语句就是触发这个迭代器的功能呢
  1. for i in "chenshiba":
  2. print(i)
  3. --------------------------
  4. c
  5. h
  6. e
  7. n
  8. s
  9. h
  10. i
  11. b
  12. a

字典_迭代

  1. linsk ={"name": "张三", "age":20, "sex":"男", "color":"red"}
  2. for each in linsk:
  3. print("%s ---> %s" % (each, linsk[each]))
  4. -------------------
  5. name ---> 张三
  6. age ---> 20
  7. sex --->
  8. color ---> red

iter() next()迭代器

  1. string = "chenshiba"
  2. ti = iter(string)
  3. print(next(ti))
  4. print(next(ti))
  5. print(next(ti))
  6. print(next(ti))
  7. ------------------- # 不会在往下执行,, 如果后面没有了数据就会提示报错 StopIteration
  8. c
  9. h
  10. e
  11. n
  1. while True:
  2. try:
  3. print(next(ti))
  4. except:
  5. break
  6. while True:
  7. try:
  8. print(next(ti))
  9. except StopIteration:
  10. break
  11. -------------------
  12. c
  13. h
  14. e
  15. n
  16. s
  17. h
  18. i
  19. b
  20. a

-iter() -__iter()表示魔法方法的迭代器

  1. class Fibs:
  2. def __init__(self, n=20):
  3. self.a = 0
  4. self.b =1
  5. self.n = n
  6. def __iter__(self):
  7. return self
  8. def __next__(self):
  9. self.a, self.b = self.b, self.a + self.b
  10. if self.a > self.n:
  11. raise StopIteration
  12. return self.a
  13. f1 = Fibs()
  14. for each in f1:
  15. if each <= 20:
  16. print(each)
  17. else:
  18. break
  19. -----------------------------
  20. 1
  21. 1
  22. 2
  23. 3
  24. 5
  25. 8
  26. 13

升级版 , 可自定义参数

  1. class Fibs:
  2. def __init__(self, n=20):
  3. self.a = 0
  4. self.b =1
  5. self.n = n
  6. def __iter__(self):
  7. return self
  8. def __next__(self):
  9. self.a, self.b = self.b, self.a + self.b
  10. if self.a > self.n:
  11. raise StopIteration
  12. return self.a
  13. f1 = Fibs(100)
  14. for each in f1:
  15. print(each)
  16. -------------------------
  17. 1
  18. 1
  19. 2
  20. 3
  21. 5
  22. 8
  23. 13
  24. 21
  25. 34
  26. 55
  27. 89