例子一
# 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 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
例子三
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
for i in PowTwo(5):
print(i)
输出
1 2 4 8 16 32
执行
>>> 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
例子四
返回所有奇数
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