Pyhton iterator and Generator

Source: Internet
Author: User
Iterative use:

1. iteration is more efficient than directly using list traversal. For example, the list returned by the dictionary's keys function and the iterator returned by iterkeys.

2. The reversed () built-in function returns an iterator for reverse access. The parameter must be a sequence.

3. enumerate: returns an iterator with an index value.

4. Replace for eachline in myfile with for eachline in myfile. readlines ():

5,Note:: The sequence cannot be changed during the iteration process. Otherwise, problems may occur and iteration errors may occur.

6. You can define a class and use it iteratively. However, you need to define the method __iter __, next.

7,

 

Use of generators:

1. The yield keyword can block function execution and save the current execution environment. The entire package is called a generator.

2. The generator can be created by calling the generator function. A generator function is a function that contains the keyword yield.

3. The generator can be executed through. Next. Run the code once until the yield keyword is stopped and the value of the expression following the yield keyword is returned.

4. You can call the send () function to send messages to the generator. A = yield L: Assign the input parameter of send to.

5. Throw: allow the client to pass in any exceptions to be thrown.

6. Similar to throw, it only throws a specific exception: generatorexit.

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.