Beginner python--list generation, generators, and iterators

Source: Internet
Author: User
Tags iterable

I. List-generated

If there is a requirement now: how do I quickly generate a list [1,2,3,4,5,6,7,8,9,10]?

In the case where the list generation is not known, this may be written:

A=[1,2,3,4,5,6,7,8,9,10]

What if you want each value to be +1? This may be the case:

 for inch Enumerate (a):     +=1Print(a)

Not convenient, here's a quick way to generate a list: List-generation. This means that the list is generated immediately.

Generate a list of 1 to 10:

 for  in range ()print(a)#  output:[1, 2, 3, 4, 5, 6, 7, 8 , 9, 10]

Generate a 2~20 list of even numbers:

 for  in Rang (1,11)]print(a)#  output:[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

It is equivalent to:

A=[]for in# List-generated    a.append (i*2)print(a)

The generated list already exists in memory.

Second, generator

With list generation, we can create a list directly. However, with memory limitations, the list capacity is certainly limited. Also, creating a list of 1 million elements takes up a lot of storage space, and if we just need to access the first few elements, the vast majority of the space behind it is wasted.

So, if the list element can be calculated according to an algorithm, can we continue to calculate the subsequent elements in the process of the loop? This eliminates the need to create a complete list, saving a lot of space. In Python, this side loop computes the mechanism, called the generator: Generator.

To create a generator, simply change [] to () in the list-generated form.

 for inch # List-generated Print (b) C  for inch # Generator Print (c) # Output: [0, 2, 4, 6, 8, ten,, +, +]<generator object <genexpr> at 0x000001d0089b45c8>

Output C, the data type description and its memory address are obtained.

The generator only nominally generates a list, but actually does not occupy that much memory, and the generator generates the corresponding data only when it is called.

If you want to print the data for the generator, you need the. __next__ () method

 print  (c.< Span style= "COLOR: #800080" >__next__  ()) #   Output first number  0  print  (C.__next__  ()) #   output second number  1print  (C.__next__  ()) #   output third number  2print  (c . __next__  ()) #   output fourth number  3 print  (C.__next__  ()) #   output fifth number  4  

What if I just need the last data? Can I output it directly?

Sorry, No. Moreover, the generator's data can only be accessed from the back, not from the back, only one value in memory, that is, the data that has been accessed cannot be accessed again.

If the generator has a lot of data, to all output, there is no easy way to do?

Sorry, no, you can only output one at a.

Of course, it is called constantly as above. __next__ () or too much, you can use for to iterate over it (the generator is also an iterative object):

 for  in range (+)) for in G:    print(n)

So, I want the generator to have eggs??

Still a little bit of egg, the generator is generally dependent on the function implementation, for example, I first define a function fib (), the function defines the sequence of the calculation rules

 def   FIB (max): N, a, b  = 0, 0, 1 while  n < max:  print   (b) a , b  = B, a + b n  = n + 1 return  Span style= "COLOR: #800000" > " done    #   note:  A, B = B, a + b equals: t  = (b, a + b) #   T is a tuple  a = t[0]b  = T[1) it does not have to write an explicit variable t   

If you give the fib () argument 10, it will output a series of numbers that can form a sequence:

1,1,2,3,5,8,13,21,34,55

The FIB function at this point is already very close to the generator, requiring only a yield,

 def  fib ( Max): #    "  generator   "  n,a,b  =0,0,1 while  N<max:  yield  b #yield saves the current interrupt state of the function, returns the value of the current B  a,b=b,a+b n=n+1 #   counter  return   " done   "  

At this point, the FIB (10) is a generator,

F = fib (6)print(f)<generator object fib at 0x104feaaa0>

The hardest thing to understand here is that the generator is not the same as the execution of the function. The function is executed sequentially, the statement is encountered return or the last line of the function is returned. The function that becomes generator, executes at each invocation next() , encounters a yield statement return, and executes again from the last statement returned yield .

To output its value one by one:

F=fib (e) print (f)print (f.__next__())print(f. __next__ ())print(f.__next__())print(f.__next__())

Because it can only be output one by one, and can not know the length, so there will always be a cross-border when the report an abnormal stopiteration, causing the program to stop

So you need to catch exceptions:

 while 1:    try# If no exception occurs, execute the following statement        x=Next (g        )  Print("G:", x)    except#  If an exception stopiteration is present, assign it to E, execute the following statement        print(e.value        ) break

As mentioned earlier, the generator can only fetch data one by one and break during the execution of the FIB function. What's the use?

It's awesome: You can implement concurrency in a single-threaded scenario, for example:

Import TimedefCustumer (name):Print("{0} ready to eat buns.". Format (name)) while1: Baozi=yield    #every time you run to this line, it will break        Print("The bun {0} came and was eaten by {1}". Format (baozi,name))defproducer (name): C1=custumer ("boss") C2=custumer ("Dick") C1.__next__() c2.__next__()#next is just calling yield    Print("{0} start making buns! ". Format (name)) forIinchRange (1,15,2): Time.sleep (1)        Print("made two buns.") c1.send (i)#send calls yield while sending it a valueC2.send (i+1) Producer ("Alex")
View Code

If you do it on your own interpreter, you will find that a program has three tasks running in staggered motion, which looks like three tasks at the same time.

Three, iterators

We already know that for there are several types of data that can be directly acting on a loop:

A class is a collection of data types, such as,,, list tuple , and dict set str so on;

One is generator to include the generator and yield the generator function with the band.

These objects, which can be directly applied to for the loop, are called iterative objects: Iterable .

You can use to isinstance() determine whether an object is an Iterable object.

The For loop is inherently called by the next () function:

a=[1,2,3,4,5] forXinchA:Print(x)#is exactly equivalent toIt=iter (a)# Convert a list to an iterator object while1:    Try: x=next (IT)#get the next value        Print(x)exceptstopiteration: Break #Jump out of the loop when encountering stopiteration anomalies

While the file is operating,

 for inch F:     Print (line)

Each output is actually called the next () function, which is not seen as an iterator in Python3.

Beginner python--list generation, generators, and iterators

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.