The builder in Python

Source: Internet
Author: User

What is a generator?

  The generator is a function that contains a special keyword yield. When called, the generator function returns a generator. You can use the Send,throw,close method to let the generator interact with the outside world.

The generator is also an iterator, but it is not just an iterator, it has the next method and behaves exactly the same as an iterator. So the generator can also be used in the Python loop,

How do I use it?

First look at an example:

# !/usr/bin/python # -*-coding:utf-8-*- def Flatten (nested):      for inch Nested:          for inch sublist:             yield  = [[1,2],[3,4],[5,6]] for in flatten (nested):      Print num,

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

Recursive generators:

#!/usr/bin/python#-*-coding:utf-8-*-defflatten2 (nested):Try:         forSublistinchNested: forElementinchFlatten2 (sublist):yieldelementexcept:        yieldnested forNuminchFlatten2 ([[1,2,3],2,4,[5,[6],7]]):    PrintNum

The result is: 1 2 3 2 4 5 6 7

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

First look at the following:

#!/usr/bin/python#-*-coding:utf-8-*-defsimple_generator ():yield1PrintSimple_generatordefrepeater (value): whiletrue:new= (yieldvalue)ifNew is  notNone:value =New R= Repeater (42)PrintR.next ()PrintR.send ('hello,world!')

The result is:

<function Simple_generator at 0x10c76f6e0>
42
hello,world!

Can be seen:

1) generator is a function

2) Generator has next method

3) The generator can use the Send method and external interaction.

---end---

The builder in Python

Related Article

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.