Python (ix)

Source: Internet
Author: User

A probe into life generator

What is a generator?

Can be understood as a data type that automatically implements the iterator protocol (other data types need to call their own built-in __iter__ method), so the generator is an iterative object

Generator classification and representation in Python: (Python provides generators in two different ways)

1. Generator function: general function definition, however, returns the result using the yield statement instead of the return statement. The yield statement returns one result at a time, in the middle of each result, suspends the state of the function so that the next time it leaves, it resumes execution.

2. Generator expression: similar to list derivation, however, the generator returns an object that produces results on demand, rather than building a list of results at a time

Why use Generator Builder's advantages

Python provides support for deferred operations using the generator. The so-called deferred operation refers to producing results when needed, rather than immediately producing results. This is also the main benefit of the generator.

Generator Summary:

1. is an iterative object

2. Delay calculation is realized, save memory Ah

3. The generator is essentially the same as other data types, it is the implementation of the iterator protocol, but the generator attached a delay to calculate the benefits of saving memory, the rest of the iterative objects can not be the benefit!

two generator expressions and list parsing
#三元表达式name = ' Alex ' name= ' Linhaifeng ' res= ' SB ' if name = = ' Alex ' Else ' Shuai ' Print (res)

Summarize:

1. The [] Conversion of the list parsing [] to () is the generator expression

2. List parsing and builder expressions are a convenient way of programming, except that generator expressions are more memory-efficient

3.Python not only uses the iterator protocol, but makes the for loop more general. Most built-in functions also access objects using an iterator protocol. For example, the SUM function is a python built-in function that accesses an object using an iterator protocol, and the generator implements an iterator protocol, so we can calculate the sum of a series of values directly:

1 SUM (x * * 2 for X in Xrange (4))
instead of superfluous, construct a list first:
1 sum ([x * * 2 for X in Xrange (4)]
Three Generator summary

The generator has a certain understanding of the above, we take the generator function as an example to summarize

    • syntactically similar to functions : Generator functions are almost identical to regular functions. They are all defined using DEF statements, except that the generator uses the yield statement to return a value, whereas a regular function returns a value using the return statement
    • automatically implement an iterator protocol : for generators, Python automatically implements the iterator protocol to apply to the iteration background (such as the For loop, Sum function). Since the generator implements the iterator protocol automatically, we can call its next method and, when no value can be returned, the generator automatically generates a Stopiteration exception
    • status Pending : The generator uses the yield statement to return a value. The yield statement suspends the state of the generator function, preserving enough information so that it can continue to execute from where it left off.

Advantage One: The benefit of the generator is a deferred calculation that returns one result at a time. That is, it does not produce all the results at once, which is useful for large data processing.

1 #列表解析2 sum ([I for I in Range (100000000)]) #内存占用大, the machine is prone to die 3 4 #生成器表达式5 sum (I for I in range (100000000)) #几乎不占内存

Advantage Two: Generator can also effectively improve code readability

1 #求一段文字中, where each word appears 2 def index_words (text): 3     result = [] 4     if Text:5         result.append (0) 6     for index, Lett Er in enumerate (text, 1): 7         If letter = = ": 8             result.append (index) 9     return result10 one print (Index_words (' H Ello Alex da sb '))
#求一段文字中每个单词出现的位置def index_words (text):    if text:        yield 0    for index, enumerate (text, 1):        if Letter = = ":            yield indexg=index_words (' Hello Alex da sb ') print (g) print (g.__next__ ()) print (g.__next__ ()) Print (g . __next__ ()) print (g.__next__ ()) print (g.__next__ ()) #报错

Here, there are at least two good reasons to note that using a generator is clearer than not using generator code:

    1. After using the generator, fewer lines of code are available. Keep in mind that if you want to write code pythonic, the fewer lines of code, the better the code is readable.
    2. When the generator is not used, we first see Result.append (index) For each result, and second, index. In other words, every time we see a list of append operations, just append is the result we want. When using the generator, the direct yield index, less the interference of the list append operation, we can see at a glance, the code is to return index.

This example illustrates that the rational use of generators can effectively improve code readability. As long as you fully accept the concept of the generator, you understand that the yield statement, like the return statement, returns a value. Then you can understand why using generators is better than not using generators, and understanding the use of generators can really make your code clear and understandable.

Note: The generator can only be traversed once (hen life can only be a certain number of eggs, the end of the dead)

1 population info. txt file contents 2 {' name ': ' Beijing ', ' population ': ' 3} ', ' name ': ' Nanjing ', ' Population ': 100000} 4 {' name ': ' Shandong ', ' Population ': 10000} 5 {' name ': ' Shanxi ', ' Population ': 19999} 6  7 def get_provice_population (filename): 8 with     open (filename) as F:9         F:10             P=eval (line) One             yield p[' population ']12 gen=get_provice_population (' Population information. txt ') All_ Population=sum (gen), p in gen:16     print (p/all_population) 17 executes the above code, there will be no output, because the generator can only traverse once. When we execute the SUM statement, we traverse our generator, and when we traverse our generator again, there will be no record. Therefore, the above code will not have any output. 18 19 Therefore, the only consideration for the generator is that the generator can traverse only once.


Python (ix)

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.