2018年2月25日 星期日

[ Python 常見問題 ] Build a Basic Python Iterator

Source From Here 
Question 
How would one create an iterative function (or iterator object) in python? 

How-To 
Iterator objects in python conform to the iterator protocol, which basically means they provide two methods: __iter__() and next(). The __iter__ returns the iterator object and is implicitly called at the start of loops. The next() method returns the next value and is implicitly called at each loop increment. next() raises a StopIteration exception when there are no more value to return, which is implicitly captured by looping constructs to stop iterating. 

Here's a simple example of a counter: 
  1. class Counter:  
  2.     def __init__(self, low, high):  
  3.         self.current = low  
  4.         self.high = high  
  5.   
  6.     def __iter__(self):  
  7.         return self  
  8.   
  9.     def next(self): # Python 3: def __next__(self)  
  10.         if self.current > self.high:  
  11.             raise StopIteration  
  12.         else:  
  13.             self.current += 1  
  14.             return self.current - 1  
  15.   
  16.   
  17. for c in Counter(38):  
  18.     print c  
This will print: 
3
4
5
6
7
8

This is easier to write using a generator, as covered in a previous answer: 
  1. def counter(low, high):  
  2.     current = low  
  3.     while current <= high:  
  4.         yield current  
  5.         current += 1  
  6.   
  7. for c in counter(38):  
  8.     print c  
The printed output will be the same. Under the hood, the generator object supports the iterator protocol and does something roughly similar to the class Counter

David Mertz's article, Iterators and Simple Generators, is a pretty good introduction. 

Supplement 
FAQ - What makes something iterable in python 
FAQ - In Python, how do I determine if an object is iterable? 

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...