How to use the python generator

Source: Internet
Author: User
This article mainly introduces what is a generator and how to use it. the following example shows how to use it. What is a generator?

A generator is a function that contains the special keyword yield. When called, the generator function returns a generator. You can use the send, throw, and close methods to allow the generator to interact with the outside world.

The generator is also an iteratorBut it is not just an iterator. it has the next method and has the same behavior as the iterator. So the generator can also be used in python loops,

How to use a generator?

First, let's look at an example:

The code is as follows:


#! /Usr/bin/python
#-*-Coding: UTF-8 -*-

Def flatten (nested ):
For sublist in nested:
For element in sublist:
Yield element

Nested = [[1, 2], [3, 4], [5, 6]

For num in flatten (nested ):
Print num,

The result is 1, 2, 3, 4, 5, 6.

Recursive generator:

The code is as follows:


#! /Usr/bin/python
#-*-Coding: UTF-8 -*-

Def flatten (nested ):
Try:
For sublist in nested:
For element in flatten (sublist ):
Yield element
Handle T TypeError:
Yield nested

For num in flatten ([[1, 2, 3], 2, 4, [5, [6], 7]):
Print num

Result: 1 2 3 2 4 5 6 7

Let's take a look at the nature of the generator.

First, let's take a look:

The code is as follows:


#! /Usr/bin/python
#-*-Coding: UTF-8 -*-

Def simple_generator ():
Yield 1

Print simple_generator

Def repeater (value ):
While True:
New = (yield value)
If new is not None: value = new


R = repeater (42)
Print r. next ()

Print r. send ('Hello, world! ')

Result:

The code is as follows:



42
Hello, world!

We can see that:
1) the generator is a function.
2) the generator has the next method.
3) the generator can use the send method to interact with the outside world.

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.