Python 中的迭代器

Python 中的迭代器

Python 3中的迭代器

容器与迭代器

在Python 3中,支持迭代器的容器,只要支持__iter__()方法获取一个迭代器对象既可。

我们来看几个例子.

列表迭代器

首先是列表:

>>> a = [1,2,3,4]
>>> a
[1, 2, 3, 4]
>>> type(a)
<class 'list'>

我们通过调用list的__iter__()方法来获取list的iterator:

>>> a2 = a.__iter__()
>>> a2
<list_iterator object at 0x1068d1630>

元组迭代器

元组有自己的迭代器tuple_iterator

>>> c = (1,2,3,4)
>>> type(c)
<class 'tuple'>
>>> c2 = c.__iter__()
>>> type(c2)
<class 'tuple_iterator'>
>>> c2
<tuple_iterator object at 0x105c337f0>

集合迭代器

集合的迭代器是set_iterator

>>> d = {1,2,3,4}
>>> type(d)
<class 'set'>
>>> d2 = d.__iter__()
>>> d2
<set_iterator object at 0x106b24c60>

非内建类型的迭代器

除了内建类型,我们再举个其他类型的例子。比如numpy的ndarray:

>>> b = np.ndarray([1,2,3,4])
>>> type(b)
<class 'numpy.ndarray'>
>>> b2 = b.__iter__()
>>> b2
<iterator object at 0x105c2acf8>
>>> type(b2)
<class 'iterator'>

迭代器

只要支持两个接口,就是个迭代器:

  • __iter__(): 获取迭代器自身
  • __next__(): 获取下一个迭代内容

除了使用__iter__()方法之外,也可以用内建的iter()函数来获取迭代器。

我们来看例子:

>>> a = [1,2,3,4]
>>> a2 = iter(a)
>>> a2
<list_iterator object at 0x106951630>
>>> print(a2.__next__())
1
>>> print(a2.__next__())
2
>>> print(a2.__next__())
3

下面我们取a3为a2的迭代器,返回的不是一个新迭代器,而就是a2本身:

>>> a3 = iter(a2)
>>> print(a3.__next__())
4
>>> print(a3.__next__())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

Python2的迭代器

基本上大同小异,只是名字不同。

在Python 2中,__iter__()方法是同样的,但是进行迭代的方法是next(),没有下划线。

例:

>>> a2.next()
1
>>> a2.__iter__()
<listiterator object at 0x7f7dfef6a1d0>

完整例:

>>> a = [1,2,3,4]
>>> a2 = iter(a)
>>> a2
<listiterator object at 0x7f7dfef6a1d0>
>>> b = np.ndarray([1,2,3,4])
>>> b2 = iter(b)
>>> b2
<iterator object at 0x7f7e039ff0d0>
>>> a3 = type(a2)
>>> b3 = type(b2)
>>> a3
<type 'listiterator'>
>>> b3
<type 'iterator'>
>>> isinstance(a3, b3)
False
>>> a3.__base__
<type 'object'>
>>> b3.__base__
<type 'object'>
>>> isinstance(a2,a3)
True
>>> isinstance(b2,b3)
True
>>> a2.next()
1
>>> a2.__iter__()
<listiterator object at 0x7f7dfef6a1d0>

猜你喜欢

转载自yq.aliyun.com/articles/673785