Python Basic Learning iterators and generators

Source: Internet
Author: User

There are several types of data that can directly act on a for loop

A class of geometry data types such as list, tuple, dict, set, str, etc.

The second class is generator including generators and functions with yield methods

These objects, which can directly act on a for loop, are called iterative objects iterable

We can use the law. Isinstance determines whether an object is a Iterable object

The generator can not only be used for a for loop, but can also use the next () method to continually call and return the next value until the last Stopiteration exception is thrown, indicating that the next value cannot continue to be returned

Objects that can be called by the next () method and constantly return the next value are collectively known as iterators, Iterator

The ITER () function can be used to turn an iterative object such as List,dict,str into an iterator

Generator:

features of the generator :

The generator is a function, and the parameters of the function are preserved.

When iterating to the next invocation, the parameters used are left for the first time, that is, the parameters of all function calls are preserved the first time they are called, not the newly created

The yield generator's operating mechanism:

When you ask the generator to take a number, the generator executes until the yield statement appears, and the generator

Yield parameter to you, then the generator will not continue to run down. When you ask him for the next number, he will be from the last state. Start running until the yield statement appears, give you the parameters, and then stop. So repeated

The following is the use of yield to implement the co-process:

1 defPanduan ():2      whileTrue:3CMD1 = (yield)4         Print(CMD1)5 6 defMain ():7CC =Panduan ()8Acl__next__()9      while1:Tencmd = input (">>") One cc.send (cmd) AMain ()

Python Basic Learning 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.