Analysis of the day4 iterator and generator, and analysis of the day4 Generator

Source: Internet
Author: User

Analysis of the day4 iterator and generator, and analysis of the day4 Generator

1. iterator

Iterator isOne way to access a set Element. In fact, the iterator isA listIt is only special when accessing collection elements. It has some specific functions and memory functions, and can remember the user's last state.An iterator is a way to access collection elements.And,The iterator can only move forward, not backward. Iterator object fromAccess started from the first element of the Set,Until all elements are accessed..

Specific:

(1). visitors do not need to care about the files in the iterator. They only needUse the next () methodContinue to fetch the next content;

(2). A value in the set cannot be randomly accessed., Which can only be accessed from start to end in sequence;

 

(3) You cannot accessRollback;

 

(4). It is easy to generate an iterator for a large set of data loops and saves memory.

 

Iter () is used to declare the iterator. The example is as follows:

Names = iter (["alex", "sb", 11,22, "gengchangxue"])
Print (names. _ next __())
Print (names. _ next __())
Print (names. _ next __())
Print (names. _ next __())
Print (names. _ next __())
Print (names. _ next __())

 

The running result is as follows:

Alex
Sb
11
22
Gengchangxue
Traceback (most recent call last ):
File "/home/zhuzhu/day4/iterator. py", line 7, in <module>
Print (names. _ next __())
StopIteration

From the above results, we can see that the iterator uses the _ next _ () method to traverse every element in the set. when the length of the list is exceeded, an error occurs, stoplteration (stop iteration ). The preceding set has five elements. If we go six times, an error is returned. The iterator can only traverse from the first value of an element until all elements are traversed. The intermediate process cannot be used back or take the value at a specific position in the middle.

There is only one _ next _ () method in the iterator for removing elements.

Ii. generator

Definition: A FunctionReturns an iterator for calling., Then thisFunctionIt is calledGenerator)If the function containsIncluding yield syntax,Then this function will becomeGenerator.

In fact, the generator (generator) function contains yield. yield works similarly to return, but after yield ends the local loop, it records the running status of the program and can be kept in the current state, when you call it again, it starts from here and repeats again. In addition, yield can return a value to the function, and yield can combine with send to receive the return value.

Def cash_money (amount ):
While amount> 0:
Amount-= 100
Yield 100
Print ("the loser, come to get the money again !... ")


Atm = cash_money (600)

We have written a function and called it, but the print () statement is not executed. Let's take a look at the atm type:

Print (type (atm ))

Run the following command:

<Class 'generator'>

It can be seen that atm is a generator, and the generator calls the _ next _ () method. Example:

Def cash_money (amount ):
While amount> 0:
Amount-= 100
Yield 100
Print ("the loser, come to get the money again !... ")


Atm = cash_money (600)
Print (atm. _ next __())
Print (atm. _ next __())

The role of the generator is that the programs we learned previously are serialized and executed from top to bottom. If a process in the middle is not executed, it will wait all the time, however, we can use yield to maintain the memory function. Let the program do other things, and then continue to do things when it comes back. For example, we do a big health care, and then come back to get the money.

Def cash_money (amount ):
While amount> 0:
Amount-= 100
Yield 100
Print ("the loser, come to get the money again !... ")


Atm = cash_money (600)
Print (atm. _ next __())
Print (atm. _ next __())
Print ("big health care ")
Print (atm. _ next __())

The running result is as follows:

100
Let's get the money again !...
100
Big health care
Let's get the money again !...
100

Yield is used to save the function status. It allows us to finish other tasks and continue execution. The generator is useful in some cases. For example, we want to save the status of the previous user so that the user can know the previous information at the next login. For example, in a banking system, the user must deduct the amount after obtaining the money and save the previous operation status.

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.