Python Path -12-generator

Source: Internet
Author: User

12.1List-generated

Example 1:
General Practice:
A = [0,1,2,3,4,5,6,7,8,9]

for Index,i in Enumerate (a):
A[index] *=2
Print (a)

List Built- in :

b = [i*2 for i in range (10)]
Print (b)

12.2 Generator

with List generation, we can create a list directly. However, with memory limitations, the list capacity is certainly limited. And, creating a list of the elements of the million, not only takes up a lot of storage space, if we just need to access the first few elements, then the vast majority of elements behind the space 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, which saves a lot of space. In Python , this side loop is calculated as a mechanism, called the generator:generator

12.3 list builder

b = (i*2 for i in range (10))

Summary: The list form is even without elements, also in memory of Mr. Cheng. The generator saves the algorithm, only the corresponding data is generated when called, only the current position is recorded, and only one __next__ () method is used to get the next return value of generator . 2.7 is next ()

12.4functionBuildManager

Fibonacci sequence :(Fibonacci)

In addition to the first and second numbers, any number can be added by the first two numbers : 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

The Fibonacci sequence is not written in a list, but it is easy to print it out with a function:

def fib (max):
N, a, b = 0, 0, 1
While n < max:
Print (b)
A, B = B, a + b # #相当于t = (b, A + b) # T is a tuple a = T[0] b = t[1]
n = n + 1
Return ' Done '
FIB (10)

The fib function becomes generator, just change print (b) to yield b :

If a function definition contains The yield keyword, then the function is no longer a normal function, but a generator. executes at each call to next () , encounters a yield statement return, executes again from the yield statement that was last returned

def fib (max):
N, a, b = 0, 0, 1
while n < max:
yield b
A, B = B, A + b
n = n + 1
return ' Done '

f = fib (5)
Print (f.__next__ ())
Print ("=============")
Print (f.__next__ ())

F or I in F:
Print (i)

#! Author:lanhan
def fib (max):
N, a, b = 0, 0, 1
while n < max:
yield b
A, B = B, A + b
n = n + 1
return ' Done '
Print (f.__next__ ())
Print ("=============")
Print (f.__next__ ())
Print (f.__next__ ())
Print (f.__next__ ())
Print (f.__next__ ())
Print (f.__next__ ())
Print ("====start loop======")
#for I in F:
#print (i)

the content of the error is the return content, the exception after the capture will not error:

g = fib (6)
While True:
Try:
x = Next (g)
Print (' G: ', X)
except Stopiteration as E:
Print (' Generator return value: ', E.value)
Break

The process of single-threaded implementation concurrency

#! Author:lanhan
#单线程实现并发的过程
ImportTime
defConsumer (name):# #消费者
    Print"%s ready to eat buns!"%name)
While True:
Baozi =yield

       Print"Bun [%s] came, eaten by [%s]!"% (Baozi,name))

c = Consumer ("Lanhan")
C.__next__ ()
# B1 = "Leek Stuffing"
# C.send (B1) # #调用yield and give yield value
# c.__next__ () # #调用yield
defProducer (name):# # #生产者
    c = Consumer (' A ')
C2 = Consumer (' B ')
C.__next__ ()
C2.__next__ ()
Print"I'm starting to make buns!")
forIinchRange (10):
Time.sleep (1)
Print"made 1 buns, in two halves!")
C.send (i)
C2.send (i)
Producer"Alex")

Python Path -12-generator

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.