Python iterators and generators

Source: Internet
Author: User
Tags generator wrapper

iterators

An iterative

# an iteration is a repeating process that repeats one iteration at a time, and the result of each iteration is the initial value of the next iteration  while True:  #  is simply repeated, thus not iterative    print('===>'  = [1, 2, 3= 0 while Count < Len (LI):  #  Iteration    Print (Li[count])     + = 1

two iterators
#1. Iterators    for strings, lists, and tuples, we can iterate through the elements that they contain by using an indexed method. But for dictionaries, collections, files, etc. types are
Without an index, if you want to take out the elements that are contained inside, you need an iterative approach that does not depend on the index, which is the iterator#2. Can iterate objects
An iterative object: Built-in with__iter__The object of the method. That is, obj.__iter__
as follows:'Hello'.__iter__ ().__iter__ [(a).__iter__#3. IteratorsIterator object: A built-in__iter__ also has a built-in object with the __next__ method. The file type is the iterator object open ('a.txt').__iter__() Open ('a.txt').__next__()#4. NoteAn iterator object must be an iterative object, and an iterative object is not necessarily an iterator object
use of three iterators
DIC = {'a': 1,'b': 2,'C': 3}iter_dic= dic.__iter__()#gets the iterator object, which is __iter__ and __next__, but the iterator. __iter__ () still gets the iterator itselfIter_dic.__iter__() isIter_dic#TruePrint(Iter_dic.__next__())#equivalent to Next (iter_dic)Print(Iter_dic.__next__())#equivalent to Next (iter_dic)Print(Iter_dic.__next__())#equivalent to Next (iter_dic)#print (iter_dic.__next__ ()) #抛出异常StopIteration, or End flag#with iterators, we can take values without relying on index iterations.Iter_dic = dic.__iter__() while1:    Try: K=Next (iter_dic)Print(Dic[k])exceptstopiteration: Break#This is too ugly to write, we need to catch the anomaly ourselves, control next,python can be solved with a for loop
View CodeFour for Loop
#based on the for loop, we can completely no longer rely on the index to fetch the value.DIC = {'a': 1,'b': 2,'C': 3} forKinchDIC:Print(Dic[k])#how the For loop works1: DiC that executes the in post object.__iter__() method to get an iterator object Iter_dic2: Executes next (iter_dic), assigns the resulting value to K, and then executes the Loop body code3: Repeat the process 2 until the exception stopiteration is caught, ending the loop

features of the five iterators
# Advantages:    - provides a unified, index-independent iterative    approach - lazy computing, saving memory # Disadvantages:    -Unable to get length ( Only when the next is finished will you know how many    values are there)-you can only walk back and not go backwards.

        
Generator

Lifetime Builder

The inside of the function contains yield, called the generator (generator), and does not execute the function internal code

deffunc ():Print('====>first')    yield1Print('====>second')    yield2Print('====>third')    yield3Print('====>end') G=func ()Print(g)#<generator object func at 0x00846bd0>#generators are iteratorsPrint(g.__iter__)Print(g.__next__)
Example
 #   Validation generator is also an iterator  from  collections import   Iterator  def   Test ():  Span style= "COLOR: #0000ff" >print  ( " first   " )  yield  1 #   equivalent to 1  g  = Test ()  #   print (g)  print   (Isinstance (g, Iterator))  #   result  True 
Verify that the generator is an iterator

What is the difference between the two generators and return?

    #return canonly be returned once, and yield can return multiple values to suspend/Save the function's running state

# what exactly did the yield do?      1. Yield turns the function into a generator---"Therefore, it is also an iterator (the generator is also an iterator      )2. Returns the value with return can be returned once, and      yield returns multiple 3. The state of the function while pausing and continuing the next run is saved by yield

Example:

1. Add of yield

defAdd (n, i):returnn +IdefTest (): forIinchRange (4):        yieldIG=Test () forNinch[1, 10]: G= (Add (n, i) forIinchg)## n = 1##g = (Add (n,i) for I in G) #[1, 2, 3, 4]##n = Ten##g1 = (Add (n,i) for I in (Add (n,i) for I in G))## #此处的n =10 #10, 11.12.13Print(List (g))#Results[20, 21, 22, 23]
View Code

2. Have direct next ()

A. there are direct

#have direct next (e)defEater (name):Print('{} start to eat food'. Format (name)) Food_list= []     whileTrue:food=yieldfood_listPrint('{} get {},to start eat'. Format (name, food)) food_list.append (food) e= Eater ('Tom') Next (e)#Perform this step!!!!!! Print(E.send ('Tieguanyin'))Print(E.send ('Watermelon'))Print(E.send ('Sesame Cake'))
View Code

B. There are direct

#no Next ()defInit (func):#add adorners here to replace next (e)    defWrapper (*args, * *Kwargs): Res= Func (*args, * *Kwargs) Next (res)returnResreturnWrapper@init#eater = init (eater)defEater (name):Print('{} start to eat food'. Format (name)) Food_list= []     whileTrue:food=yieldfood_listPrint('{} get {},to start eat'. Format (name, food)) food_list.append (food) e= Eater ('Tom')#Next (E) #不在此执行这一步Print(E.send ('Tieguanyin'))Print(E.send ('Watermelon'))Print(E.send ('Sesame Cake'))
View Code

Get the same result:

" " Tom start to eat food Tom get Tieguanyin, to start eat[' Tieguanyin '] tom get watermelon, to start eat[' tieguanyin ', ' Watermelon ' tom get pancake, to start eat[' tieguanyin ', ' Watermelon ', ' pancake ']'

Python iterators and generators

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.