This article mainly introduces detailed information about the iterator and generator instances in Python. For more information, see the next article. it mainly introduces detailed information about the iterator and generator instances in Python, for more information, see
Details about the iterator and generator instance in Python
This article summarizes some knowledge about the iterator and generator in Python based on different application scenarios and solutions. The details are as follows:
1. manually traverse the iterator
Application scenario: you want to traverse all elements in an iteratable object, but do not want to use a for loop.
Solution: Use the next () function and capture the StopIteration exception.
def manual_iter(): with open('/etc/passwd') as f: try: while True: line=next(f) if line is None: break print(line,end='') except StopIteration: pass
#test caseitems=[1,2,3]it=iter(items)next(it)next(it)next(it)
2. proxy iteration
Application scenario: you want to perform iterative operations directly on a container object that contains a list, tuples, or other iteratable objects.
Solution: define an iter () method to proxy iteration operations to objects inside the container
Example:
Class Node: def init (self, value): self. _ value = value self. _ children = [] def repr (self): return 'node ({! R })'. fromat (self. _ value) def add_child (self, node): self. _ children. append (node) def iter (self): # pass the iteration request to the internal _ children attribute return iter (self. _ children)
#test caseif name='main': root=Node(0) child1=Node(1) child2=Nide(2) root.add_child(child1) root.add_child(child2) for ch in root: print(ch)
3. reverse iteration
Application scenario: to reverse iterate a sequence
Solution: Use the built-in reversed () function or implement reversed () on a custom class ()
Example 1
a=[1,2,3,4]for x in reversed(a): print(x) #4 3 2 1f=open('somefile')for line in reversed(list(f)): print(line,end='')#test casefor rr in reversed(Countdown(30)): print(rr)for rr in Countdown(30): print(rr)
Example 2
Class Countdown: def init (self, start): self. start = start # conventional iteration def iter (self): n = self. start while n> 0: yield n-= 1 # reverse iteration def reversed (self): n = 1 while n <= self. start: yield n + = 1
4. selective iterations
Application scenario: to traverse an iteratable object, but not interested in some of its initial elements, skip
Solution: Use itertools. dropwhile ()
Example 1
with open('/etc/passwd') as f: for line in f: print(line,end='')
Example 2
from itertools import dropwhilewith open('/etc/passwd') as f: for line in dropwhile(lambda line:line.startwith('#'),f): print(line,end='')
5. iterate multiple sequences at the same time
Application scenario: to iterate multiple sequences at the same time, obtain one element from one sequence at a time.
Solution: Use the zip () function
from collections import Iterabledef flatten(items,ignore_types=(str,bytes)): for x in items: if isinstance(x,Iterable) and not isinstance(x,ignore_types): yield from flatten(x) else: yield x
#test caseitems=[1,2,[3,4,[5,6],7],8]for x in flatten(items): print(x)
The above is a detailed explanation of the iterator and generator instance in Python. For more information, see other related articles in the first PHP community!