Python Basics-Day 4 Learning Note-generator Generator

Source: Internet
Author: User
Tags for in range generator generator

List Builder/list resolution lists comprehension
    • Simple and flexible to create lists, usually with lambda (), map (), filter ()
    • Create a list directly from a list of generated expressions. However, if you receive content restrictions, the list size is certainly limited. And, creating a list of 1 million elements, not only takes up a lot of storage space, but if we just need to access a few elements, then the other is white space. The list generator is able to cycle one side of the computation, greatly saving a lot of space. is one of the generators.

    • Only the call can be generated. Slicing operations are not supported, only numbers can be taken by __next () ___.
Basic syntax
 for inch Iterable] or  forif cond_expr]
Case
# Example 1:  for  in range (2, 4, 6, 8, ten, 2, +, +)#  Example 3: Iteration of the Matrix for row 5 columns for  C9>in for in range (5)]print(q)
List Comp

Generator definition

The builder is an extension of the List Builder. In Python, this side of the loop calculates the mechanism , called the generator generator; each time an entry is computed, the entry is "generated" (yield), and the process becomes "lazy evaluation", So it's more efficient to use memory. In syntax, a generator is a function with a yield statement.

Application:

1. Call a value in the function and jump out of the function, next to continue calling the next value. Take the following Fibonacci retracement Fibonacci sequence as an example:

deffib (max): N, a, b= 0, 0, 1 whileN <Max:yieldB#the function of the knowledge point 1-yield returns a value to the caller and pauses execution. A, B = B, A + b#The process of re-assignment, A/b on the left is the new, the past value operation on the rightn = n + 1return " Done"    #the function of return is the return value of the exception handling that may occur when next is called. Print(FIB (10))#return to a generator: <generator object fib at 0x0000026faa8a78e0>#Knowledge point 2-how elements are invokedf = fib (10) forIinchF:Print(i)#function return value done does not print with a for loop#Knowledge Point 3-next () call in case of an exceptiong = FIB (6) whileTrue:Try: x= Next (g)#built-in method, = __next__. When a real return is reached or the function ends without more values returned, a Stopiteration exception will be thrown. So the exception needs to be handled by try ... expect ... Statement        Print('g:', X)exceptstopiteration as E:Print('Generator return value:', E.value)#E.value returns the done

2. Collaborative procedures . A synergistic program is a standalone function call that can be run, suspended or suspended, and resumed or resumed from where the program left off. There is also communication between the caller and the (callee) co-program. For example, when a co-program pauses, we can get an intermediate return value from it, and when the call goes back to the program, it can pass in additional or changed parameters, but it can still continue from where we left off, and all the states are intact. The role of the generator is to suspend a synergistic program that returns an intermediate value and continues multiple times.

1 #!usr/bin/env python2 #-*-coding:utf-8-*-3 #The effect of implementing concurrent operations in single-threaded situations through yield, or a typical producer-consumer model. This is the embryonic form of asynchronous IO later. 4 5 Import Time6 7 8 defConsumer (name):9     Print('%s prepare to eat steamed buns.'%name)Ten      whileTrue: OneBaozi =yield   #yield A         Print('Bun [%s] came, eaten by [%s]'%(baozi,name)) -  -  the defproducer (name): -c = Consumer ('A')#turning a function into a generator -C2 = Consumer ('B') -C.__next__()#call the generator for the first time +C2.__next__() -     Print('Lao Tzu began to eat steamed buns! ') +      forIinchRange (10): ATime.sleep (1) at         Print("made 2 buns! ") -C.send (i)#the function of send is to wake up and give the yield a value, next just calls yield - c2.send (i) -  -Producer"Alex")
The simplest process-eating buns example

Reference

1. Python Road, Day4-python Foundation 4 (new edition), http://www.cnblogs.com/alex3714/articles/5765046.html

2. "Python Core Programming V2" page 205-207; page 305-307

Python Basics-Day 4 Learning Note-generator Generator

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.