Python圈Python基础

Python12--迭代器

2020-09-01  本文已影响0人  伊洛的小屋
1.迭代器

要理解迭代器,首先需要明白迭代器和可迭代对象的区别。一个一个读取、操作对象称为迭代,Python 中,可迭代(Iterable)对象就是你能用for循环迭代它的元素,比如列表是可迭代的

(yiluo) ➜  Code python3
Python 3.7.5 (default, Nov 29 2019, 14:32:46)
[Clang 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> skills = ['一骑当千','单刀赴会','青龙偃月','刀锋铁骑']
>>> for skill in skills:
...     print(skill)
...
一骑当千
单刀赴会
青龙偃月
刀锋铁骑

你能用 next 函数不断的去获取它的下一个值,直到迭代器返回 StopIteration异常。所有的可迭代对象都可以通过 iter 函数去获取它的迭代器

# 作者:伊洛Yiluo 公众号:伊洛的小屋
# 个人主页:https://yiluotalk.com/
# 博客园:https://www.cnblogs.com/yiluotalk/
>>> skills = ['一骑当千','单刀赴会','青龙偃月','刀锋铁骑']
>>> skill = iter(skills)
>>> print(skill)
<list_iterator object at 0x1037ea5d0>
>>> next(skill)
'一骑当千'
>>> next(skill)
'单刀赴会'
>>> next(skill)
'青龙偃月'
>>> next(skill)
'刀锋铁骑'
>>> next(skill)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
2.另一种实现方式
>>> class Test:
...     def __init__(self, a, b):
...         self.a = a
...         self.b = b
...     def __iter__(self):
...         return self
...     def __next__(self):
...         self.a += 1
...         if self.a > self.b:
...             raise StopIteration()
...         return self.a
...
>>> test = Test(0, 5)
>>> next(test)
1
>>> next(test)
2
>>> next(test)
3
>>> next(test)
4
>>> next(test)
5
>>> next(test)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 10, in __next__
StopIteration

欢迎下方【戳一下】【点赞】
Author:伊洛Yiluo
愿你享受每一天,Just Enjoy !

上一篇下一篇

猜你喜欢

热点阅读