Python疊代器

Python中的疊代器只是一個可以疊代的物件。一個將一次返回資料的物件或一個元素。

`iter()`函式(這又呼叫`__iter__()`方法)返回一個疊代器。

通過Python中的疊代器迭代

``````# define a list
my_list = [4, 7, 0, 3]

# get an iterator using iter()
my_iter = iter(my_list)

## iterate through it using next()

#prints 4
print(next(my_iter))

#prints 7
print(next(my_iter))

## next(obj) is same as obj.__next__()

#prints 0
print(my_iter.__next__())

#prints 3
print(my_iter.__next__())

## This will raise error, no items left
next(my_iter)
``````

``````>>> for element in my_list:
...     print(element)
...
4
7
0
3
``````

迴圈如何實際工作？

``````for element in iterable:
# do something with element
``````

``````# create an iterator object from that iterable
iter_obj = iter(iterable)

# infinite loop
while True:
try:
# get the next item
element = next(iter_obj)
# do something with element
except StopIteration:
# if StopIteration is raised, break from loop
break
``````

在Python中構建自己的Iterator

`__iter__()`方法返回疊代器物件本身。如果需要，可以執行一些初始化。

`__next__()`方法必須返回序列中的下一個專案(資料物件)。 在到達結束後，並在隨後的呼叫中它必須引發`StopIteration`異常。

``````class PowTwo:
"""Class to implement an iterator
of powers of two"""

def __init__(self, max = 0):
self.max = max

def __iter__(self):
self.n = 0
return self

def __next__(self):
if self.n <= self.max:
result = 2 ** self.n
self.n += 1
return result
else:
raise StopIteration
``````

``````>>> a = PowTwo(4)
>>> i = iter(a)
>>> next(i)
1
>>> next(i)
2
>>> next(i)
4
>>> next(i)
8
>>> next(i)
16
>>> next(i)
Traceback (most recent call last):
...
StopIteration
``````

``````>>> for i in PowTwo(5):
...     print(i)
...
1
2
4
8
16
32
``````

Python無限疊代器

``````>>> int()
0

>>> inf = iter(int,1)
>>> next(inf)
0
>>> next(inf)
0
``````

``````class InfIter:
"""Infinite iterator to return all
odd numbers"""

def __iter__(self):
self.num = 1
return self

def __next__(self):
num = self.num
self.num += 2
return num
``````

``````>>> a = iter(InfIter())
>>> next(a)
1
>>> next(a)
3
>>> next(a)
5
>>> next(a)
7
``````