python--Generators and iterators

Source: Internet
Author: User
Tags for in range ming pprint

Generator (Generator)

Before we look at the generator, let's look at the list-building.

If we want a 12,22,32 ... 102 Composition of the list, we can consider the following practices:

1  for  in range (1,one)]2 print (a)

Output:

——————————

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

——————————

This is one of the simplest forms of python, and we can get a list quickly in this way. In fact, he still has a lot of gameplay:

1 Import Pprint 2 a=[(x, y) for in range (3for in"ABC"  ]3pprint.pprint (a) #pprint () is to make the printed result more beautiful, not too long 45  for  in range (-5,5)]6 print (b)

Output:

————————

[(0, ' a '),
(0, ' B '),
(0, ' C '),
(1, ' a '),
(1, ' B '),
(1, ' C '),
(2, ' a '),
(2, ' B '),
(2, ' C ')]
[5, 4, 3, 2, 1, 0, 1, 2, 3, 4]
————————

Let's take a look at the generator. The method of getting a generator is actually very simple, we just need to change the [] in the list generation to (), as follows:

1  for  in range (1,one))2 print (a)
View Code

Output:

——————————

<generator Object <genexpr> at 0x0398baa8>

——————————

We print a and get the result that A is a generator and his memory address is: 0X0398BAA8. There is obviously no data generated in a, and the list generation is very different. The list generation generates all the data in the list in memory at run time (even if we don't use that data), and when we're not using the data, the generator doesn't generate any data. It looks like the generator is quite lazy. Yes, we call the generator an inert sequence. But the laziness here is commendatory, because he saves memory space.

How do you get the generator to generate data? Answer: Next

1A= (x*x forXinchRange1, One))2 print (a.__next__ ())3 print (a.__next__ ())4 print (a.__next__ ())5 print (a.__next__ ())6 print (a.__next__ ())7 print (a.__next__ ())8 print (a.__next__ ())9 print (a.__next__ ())Ten print (a.__next__ ()) One print (a.__next__ ()) A print (a.__next__ ()) -#上面的11个a. __next () __ Change to 11 next (a) effect unchanged

Output:

——————

1

4

9

16

25

36

49

56

81

100

Error:stopiteration

——————

We see 10 numbers in the generator, we call 11 times next (or __next__), each call, the generator generates the next value and releases the previous value, and throws a stopiteration error after all has been generated. You can see that this is a great savings on the memory of the computer. But the way you call next every time isn't necessarily too silly. Is there a better way? Answer: For loop.

1  for  in range (1,one))2 for in A:3     Print (i)
View Code

Output:

————————

1
4
9
16
25
36
49
64
81
100

————————

That's a lot more elegant.

What is the principle of the above-mentioned generator with parentheses in the form of a list? Why would he be able to produce data lazily? This involves yield.

Let's look at one of the following functions:

1 def doublenum (n): 2      for  in range (1, n+1):3         if i%2= =0  :4           print (i)5 doublenum (ten)

Output Result:

————————

2

4

6

8

10

————————

I'll change him here:

1 def doublenum (n): 2      for  in range (1, n+1):3         if i%2= =0 : 4            yield i #把原来的print (i) was changed to yield I 5 print (Doublenum (ten))

Output:

————————

<generator Object Doublenum at 0x02ae7698>

————————

What happened!!! It becomes a generator! , let's see if we can use next to generate the data?

1 def doublenum (n):2      forIinchRange1, n+1):3         ifi%2==0:4            yield(i)5G=doublenum (Ten)6Print"the way of the loop:")7  forIinchg:8 print (i)9Print"\nnext the way:")Ten Print (Next (g)) One Print (Next (g)) A Print (Next (g)) - Print (Next (g)) -Print (Next (g))

Output:

————————

The way of the loop:

2

4

6

8

10

Next way:

2

4

6

8

10

Stopiteration

————————

It turns out he's actually a generator.

In fact, the generator is a function or class containing yield (see?). The function above contains yield, so he programmed the generator. )

To make you understand the generator, let me write an interesting thing:

1 def Consumer (name):2Print"%s ready to eat steamed buns ..."%name)3      whileTrue:4Baozi=yield5Print"%s has finished eating%s"%(Name,baozi))6 def producer (baozi_name1,baozi_name2):7Xiaoming=consumer ("Xiao Ming")8Xiaohong=consumer ("Little Red")9 xiaoming.__next__ ()Ten xiaohong.__next__ () OnePrint"I made a%s and a%s, sent to Xiao Ming and Xiao Hong"%(baozi_name1,baozi_name2)) A xiaoming.send (baozi_name1) - xiaohong.send (baozi_name2) -  the  forIinchRangeTen): -Producer"Leek Bag","Milk Yellow Bag")
View Code

Output:

————————

Xiao Ming is ready to eat steamed buns ...
Little red ready to eat steamed buns ...
I made a leek bag and a milk yellow bag, sent to Xiao Ming and Xiao Hong
Xiao Ming has finished his leek bag.
Little Red has eaten the milk yellow bag.
Xiao Ming is ready to eat steamed buns ...
Little red ready to eat steamed buns ...
I made a leek bag and a milk yellow bag, sent to Xiao Ming and Xiao Hong
Xiao Ming has finished his leek bag.
Little Red has eaten the milk yellow bag.
Xiao Ming is ready to eat steamed buns ...
Little red ready to eat steamed buns ...
I made a leek bag and a milk yellow bag, sent to Xiao Ming and Xiao Hong
Xiao Ming has finished his leek bag.
Little Red has eaten the milk yellow bag.
Xiao Ming is ready to eat steamed buns ...
Little red ready to eat steamed buns ...
I made a leek bag and a milk yellow bag, sent to Xiao Ming and Xiao Hong
Xiao Ming has finished his leek bag.
Little Red has eaten the milk yellow bag.
Xiao Ming is ready to eat steamed buns ...
Little red ready to eat steamed buns ...
I made a leek bag and a milk yellow bag, sent to Xiao Ming and Xiao Hong
Xiao Ming has finished his leek bag.
Little Red has eaten the milk yellow bag.
Xiao Ming is ready to eat steamed buns ...
Little red ready to eat steamed buns ...
I made a leek bag and a milk yellow bag, sent to Xiao Ming and Xiao Hong
Xiao Ming has finished his leek bag.
Little Red has eaten the milk yellow bag.
Xiao Ming is ready to eat steamed buns ...
Little red ready to eat steamed buns ...
I made a leek bag and a milk yellow bag, sent to Xiao Ming and Xiao Hong
Xiao Ming has finished his leek bag.
Little Red has eaten the milk yellow bag.
Xiao Ming is ready to eat steamed buns ...
Little red ready to eat steamed buns ...
I made a leek bag and a milk yellow bag, sent to Xiao Ming and Xiao Hong
Xiao Ming has finished his leek bag.
Little Red has eaten the milk yellow bag.
Xiao Ming is ready to eat steamed buns ...
Little red ready to eat steamed buns ...
I made a leek bag and a milk yellow bag, sent to Xiao Ming and Xiao Hong
Xiao Ming has finished his leek bag.
Little Red has eaten the milk yellow bag.
Xiao Ming is ready to eat steamed buns ...
Little red ready to eat steamed buns ...
I made a leek bag and a milk yellow bag, sent to Xiao Ming and Xiao Hong
Xiao Ming has finished his leek bag.
Little Red has eaten the milk yellow bag.

————————

Above is a producer of consumer models, producers continue to produce steamed buns, consumers continue to eat steamed buns, so that the program in two functions alternating between the execution, because the speed of operation is very fast, gives users a parallel illusion. This enables "false parallelism" in the single-threaded scenario. This is actually called the co-process. Note that the Send function has two functions:

1. Re-awaken the consumer so that it continues to execute.

2. Send the parameter to yield and yield assigns it to the bun variable.

In general: The generator is a lazy function, each time the next will make the function to yield, and then stop until the next next wake up, wake up after the last yield to continue execution.

Iterators (Iterator)

Iterators in Python are very different from iterators in C + + and cannot be compared. Judging whether an object is an iterator in Python is a way to see if the object has next () (or __next__ ()), and there is no. So the generator mentioned above is an iterator.

For the grasp of the iterator you can master this point, the main master generator.

Summarize

Yield can realize the association, mainly to understand the use of yield.

python--Generator and iterator

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.