An explanation of iterators and builder instances in Python

Source: Internet
Author: User
This article mainly describes the python in the iterator and the builder instance of the relevant information, the need for friends can refer to the following

An explanation of iterators and builder instances in Python

This paper summarizes some of the relevant knowledge of iterators and generators in Python by means of different application scenarios and their solutions, as follows:

1. Manually traverse the iterator

Scenario: You want to traverse all the elements in an iterative object, but do not want to use a for loop

Solution: Use the next () function and catch the stopiteration exception


Def manual_iter (): With  open ('/etc/passwd ') as F:    try: When      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)

2. Agent iterations

Scenario: You want to perform an iterative operation directly on a container object that contains a list, tuple, or other object that can be iterated

Solution: Define a ITER () method that proxies an iterative operation to an object 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) :    #将迭代请求传递给内部的_children属性    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

Scenario: Want to iterate over a sequence in reverse

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 (+)):  print (RR) for RR in Countdown (+):  print (RR)

Example 2


Class countdown:  def init (self,start):    self.start=start  #常规迭代  def iter (self):    N=self.start While    n > 0:      yield n      n = 1  #反向迭代  def reversed (self):    n=1 while    n <= self.start :      yield n      n +=1

4. Selective iterations

Scenario: You want to iterate over an iterative object, but you're not interested in some of the elements it starts with, want to 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

Scenario: You want to iterate over multiple sequences at once to take one element from a sequence at a time

Solution: Use the zip () function

6. Iterations of elements on different sets

Scenario: You want to perform the same action on multiple objects, but these objects are in different containers

Solution: Use the Itertool.chain () function

7. Expand a nested sequence

Scenario: You want to expand a sequence of nested layers into a single-level list

Solution: Use a recursive generator that contains a yield from statement

Example


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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.