1. Manually traverse the iterator
Use the next function and captureStopIteration异常。
def Manual_iter (): With open ('./test.py') as F: try : while True: = Next (f) print line except stopiteration: Pass
The next function can also specify a value to mark the end
def Manual_iter (): With open ( " ./test.py ) as F: try : while true:line /span>= Next (f, None) if line ==
None:
break print line except< /span> stopiteration: pass
Using the For loop operation iterator does not have to consider the stopiteration exception, and the underlying automatically handles these details
2. Agent Iteration
使用iter来返回指定对象的迭代,iter(s)
Simply by calling the s.__iter__()
method to return the corresponding iterator object
classNode:def __init__(self, value): Self._value=value Self._children= [] def __repr__(self):return 'Node ({!r})'. Format (self._value)defAdd_child (Self, Node): Self._children.append (node)def __iter__(self):returniter (Self._children) Node1= Node (1) Node2= Node (2) Root= Node ('Root') Root.add_child (node1) root.add_child (Node2)
i = iter (root)
Print Next (i)
Print Next (i)
For N in Root:
Print n
It is important to note that __iter__ () can use a for loop, but it cannot be called directly using next (), and if you want to use next, you must first call Root.iter ()
3. Implementing an Iterator protocol
The Python iteration protocol requires a __iter__()
method to return a special iterator object that implements the next method, noting that Python3 is the __next__ method. and StopIteration
the completion of the iteration is identified by an exception. The simplest way is to use it in the proxy iteration. Another way is __iter__ () returns the object itself, which implements the next () method.
classFib (object):def __init__(self): SELF.A, self.b= 0, 1#Initialize two counters A, B def __iter__(self):returnSelf#The instance itself is an iterative object, so it returns itself defNext_ (self): # in Python3, for __next__ () self.a, self.b= self.b, SELF.A + self.b#Calculate Next Value ifSELF.A > 100000:#conditions for exiting a loop Raisestopiteration ()returnSelf.a#returns the next value
4. Reverse Iteration
Using the built-in reversed enables reverse iterations, provided the object size can be determined, or the __reversed__ method is implemented.
A = [1, 2, 3, 4] for in reversed (a): print x
Using the __reversed__ method
classCountdown:def __init__(self, start): Self.start=Start#Forward iterator def __iter__(self): n=Self.start whilen >0:yieldN N-= 1#Reverse iterator def __reversed__(self): n= 1 whileN <=Self.start:yieldN N+ = 1 forRrinchReversed (Countdown (30)): PrintRR forRrinchCountdown (30): PrintRr
5. Iterator slicing
Slicing an iterator can be done using the Itertools.islice () method, which islice()
returns an iterator that can generate the specified element by traversing and discarding all the elements until the slice starts the index position. The return element is then started, and the slice ends at the index position.
def count (n): while True: yield N + =1 = count (ten)import itertools for in Itertools.islice (c, ten): print x
Python Learning notes-iterators and generators