Python 中的迭代器
阿新 • • 發佈:2018-11-28
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>