Python base----builder, ternary expression, list-generated, generator-expression

Source: Internet
Author: User

Python Development Foundation-day9-Generator, ternary expression, list generation, generator expression

Generator

Generator function: The function body contains the yield keyword, the result of which the function executes is the generator, which is essentially an iterator.

def foo ():    print (' first------> ')    yield 1    print (' second-----> ')    yield 2    print (' Third-----> ')    yield 3    print (' fouth-----> ') G=foo () from collections Import Iteratorprint (Isinstance (g, Iterator)) print (g)

Yield Features:

1. Similar to return, can return a value, but the difference is that there can be multiple yield, each yield can return a value, and return can only return once the value is ended

2. Encapsulates the __iter__ and __next__ methods for the function, and makes the result of the function's execution an iterator

3. Follow the value of the iterator obj.__next__ (), the execution of the triggered function, the function pause and the continuation of the state are saved by yield

Use of generators

def foo ():    print (' first------> ')    yield 1    print (' second-----> ')    yield 2    print (' Third-----> ')    yield 3    print (' fouth-----> ') g=foo () print (g.__next__ ()) print (g.__next__ ()) Print (g.__ Next__ ()) # Print (g.__next__ ()) output result first------>1second----->2third----->3

The first time g.__next__ () pauses after the first yield of the function body and executes the preceding instruction

The second g.__next__ () pauses at the end of the second yield of the function body and executes the preceding instruction

The third time g.__next__ () pauses after the third yield of the function body and executes the preceding instruction

If you come to the fourth time g.__next__ () method, the Stopiteration hint error will be thrown

For Loop call: For will automatically handle stopiteration when encountering Stopiteration auto stop

For I in G: #obj =g.__iter__ ()   #obj. __next__ ()    print (i)

Output results

First------>1second----->2third----->3fouth----->

If the generator function does not assign a value variable, then each execution is a new generator function, and there is no iterative effect, as follows:

def foo ():    print (' first------> ')    yield 1    print (' second-----> ')    yield 2    print (' Third-----> ')    yield 3    print (' fouth-----> ') print (foo (). __next__ ()) Print (foo (). __next__ ()) Print (foo (). __next__ ()) Output first------>1first------>1first------>1

Using Print to test the Foo function, you will find that the same time output of the Foo function, memory address and different

Print (foo (), foo (), foo ()) Output result: <generator object foo at 0x00000251392f1e60> <generator object Foo at 0x00000251392f1db0> <generator object Foo at 0x00000251392f1eb8>

Generator Example: One yield returns multiple values

def countdown (n):    print (' Starting countdown ') while    n > 0:        yield n        n-=1    print (' Stop Countdown ' ) G=countdown (5) for I in G:    print (i) output starting Countdown54321stop Countdown

Generator emulation Linux command: tail-f a.txt |grep ' error ' |grep ' 404 '

When you enter a string in the A.txt file, if it contains an error and contains 404, the line will be printed, and the other is not printed

Import timedef tail (filepath,encoding= ' Utf-8 '): With    open (filepath,encoding=encoding) as F:        F.seek (0,2) While        True:            # f.seek (0, 2) #不行            line=f.readline ()            if line:                # print (line,end= ")                yield Line            Else:                time.sleep (0.5) def grep (Lines,pattern): for-line in    lines: if-pattern in line        :            # Print (line)            yield lineg1=tail (' a.txt ') g2=grep (G1, ' Error ') G3=grep (G2, ' 404 ') For i in G3:    print (i)

Three-dimensional expression

Simplify code: Compare the size of two numbers, and you can do this with the following if statement

X=2y=3if x > Y:    print (x) Else:    print (y)

Use ternary expressions: can be simplified into one line to resolve

res= ' x ' if x > y else ' y ' Print (res)

The ternary expression is ' x ' if x > y else ' y '

When the condition is true, then the value to the left of the output condition, when the condition is false, outputs the right value

Example:

def max2 (x, y):    # if x > y: #     return x    # Else:    #     return y    return x if x > y else yprint (MAX2)

List-Generated

Simplifying the amount of code generated for a list

such as: Convert the string s= ' hello ' into uppercase, and convert each character into a list element, i.e. [' H ', ' E ', ' l ', ' l ', ' O ']

Normal Loop code:

s= ' Hello ' l=[]for i in S:    res=i.upper ()    l.append (res) print (l)

List Parsing code:

s= ' Hello ' res=[i.upper () for I in S]print (res)

Simple code generation can be simplified by using list parsing

List-Generated Description:

Example:

L=[1,31,73,84,57,22]print ([i-I in L if I >]) #l列表中大于50的元素生成一个新列表print ([i-I in L if I <]) #l列表中小于 50 of elements generate a new list
print ([I for I in L if i > I <]) #l列表中大于20小于50的元素生成一个新列表

Builder expression

Similar to the list generation, except that the brackets are replaced with parentheses, each execution of next will output an element that consumes less memory and consumes only one element of memory at a time.

g= (I for I in range) print (g)    #生成器print (Next (g))    #每次执行next (g) to output an element print (Next (g)) print (Next (g)) Print (Next (g)) output <generator object <genexpr> at 0x00000205ffe91e60>0123

Python foundation----builder, ternary expression, list-generated, builder-expression

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.