Python "Iterator builder list Derivation"

Source: Internet
Author: User
Tags generator generator iterable

Python "Iterator builder list Derivation"

One, iterator

1. iterators
How to take a value from a list or dictionary
Index, key
For loop
All the values that can be used for a loop are iterated
Iterative protocols: Internally containing __iter__ methods are iterative
Iterator protocol: Internally containing the __iter__ method and the __next__ method are iterators
Print (dir ([+])) Lst_iter = [1,2,3].__iter__ () Print (lst_iter.__next__ ()) print (lst_iter.__next__ ()) Print (Lst_ ITER.__NEXT__ ()) for i in []:   #  [1,2,3].__iter__ ()    print (i) L = [1,2,3]lst_iter = iter (l)   # l.__ ITER__ () while True:    try:        print (Next (lst_iter)) # lst_iter.__next__ ()    except stopiteration:        break

  

2. What is an iterative
What is an iterator = = = "iterator = iter (iterative), with a __next__ method
Maximize the benefits of iteration to save memory
From collections Import Iterable,iteratorprint (range (100000000)) print (Isinstance (range (100000000), iterable)) # Determines whether the current is an iterative print (Isinstance (range 100000000), Iterator) #是不是一个迭代器py2 range #不管range多少 generates a list that will be used to store all the values Py3 Range #不管range多少 does not actually generate any one value

3, the advantages of iterators

A, save memory
b, take a value can carry on the next calculation, and do not have to wait until all the values are calculated to start the next operation--fast
4, the characteristics of iterators: lazy operation

Second, generator Generator

The iterator you write is a generator

Two mechanisms for writing your own generator (iterator): Generator function Builder expression

1. Generator function---A function with yield is a generator function

  

def func ():    print (' * * * *)    yield 1    print (' ^^ ^^ ')    yield 2   # Record the current position, wait for next next to trigger the function's state G = func () Print ('---', Next (g)) print ('--', Next (g)) # The Call of the generator function does not trigger the execution of the code, but instead returns a generator (iterator) # want the generator function to execute with nextdef cloth_g (num): For    i in range (num):        yield ' cloth%s '%ig = Cloth_g (() print (Next (g)) print (Next (g)) print (next)

2. Example of using generator to listen for file input

Import Timedef Listen_file (): With    open (' userinfo ') as F: When        True: line            = F.readline () #readline does not automatically stop the C10/>if Line.strip ():                yield Line.strip ()            Time.sleep (0.1) G = Listen_file () for line in G:    print (line)

3. Send keyword

def func ():    print (11111)    Ret1 = yield 1    print (22222, ' Ret1: ')    Ret2 = yield 2    print (33333, ' Ret2: ', RET2)    Yield 3g = func () ret = next (g) print (ret) print (G.send (' Alex '))  # Pass a parameter to the internal print of the generator function during next execution (g.send (' King boss ') # to pass a value in a generator there is an activation process that must be triggered with next for the first time.

Build instance: Calculate moving Average

#月度 Day Average income def average ():    Sum_money = 0 Days    = 0    avg = 0 while    True: money        = yield avg        Sum_money + = Money Day        + = 1        avg = SUM_MONEY/DAYG = average () Next (g) print (g.send) print (g.send) print (G.send ( 600))

5. Pre-excitation generator

Def init (func):    def Inner (*args,**kwargs):        ret = func (*args,**kwargs)        next (ret)  # Pre-activate        return ret    return Inner@initdef average ():    Sum_money = 0 Day    = 0    avg = 0 and    True: money        = yield avg
   
    sum_money + = Money Day        + = 1        avg = SUM_MONEY/DAYG = average () print (G.send ()) print (g.send) print ( G.send (600))
   

6. Yield from

Def generator_func ():    yield from range (5)    yield from ' hello ' to    I in range (5):        yield I for    J in ' Hello ':        yield JG = Generator_func () for I in Generator_func ():    print (i) G1 = Generator_func () g2 = Generator_fun C () Next (Generator_func ()) Next (Generator_func ())

  

6. How to take a value from the generator
The first: Next can stop at any time for the last error
Print (Next (g))
Print (Next (g))
Second: The For loop is traversed from beginning to end without encountering a break, and return does not stop
For I in G:
Print (i)
Third: A strong transfer of the list tuple data type to load all the data into memory. Very wasted memory
Print (g)
Print (List (g))

7. Summary:
Generator functions are a means for our Python programmers to implement iterators
The main feature is that the yield is included in the function
Calling a generator function does not execute the code in this function just to get a generator (iterator)
The code inside the function is executed only when the value is taken from the generator, and each fetch of data is executed to get that data.
The way to get data includes the following: Forced conversions for next send loop data types
A convenient way to yield the return value, if it is an iterative iteration of the loop, and to return each element in the iterated data can be used yield from
When using send, pre-excitation is required after the generator is created, which can be done using adorners
Generator features: Save memory lazy operations
Generators are used to solve the decoupling between memory problems and program functions

8. List Deduction formula

  

New_lst = []for i in range    ]: new_lst.append (i**2) print (new_lst) print ([i**2-I in range]) L = [1,2,3,-5,6,20, -7]print ([i%2 for I in range]) L = [1,2,3,-5,6,20,-7]print ([Num for num in L if num%2 = = 1]) #30以内所有能被3整除的数print ([I for I in range (if i%3 ==0]) #30以内所有能被3整除的数的平方print ([i**2-I in range] if i%3 ==0]) #找到嵌套列表中名字含有两个 all names of ' e ' names = [[' To M ', ' Billy ', ' Jefferson ', ' Andrew ', ' Wesley ', ' Steven ', ' Joe ',         [' Alice ', ' Jill ', ' Ana ', ' Wendy ', ' Jennifer ', ' Sherry ', ' Eva ']]print ([name for name_lst in names for name in Name_lst if Name.count (' e ') = = 2])

9. Generator expression

L = [I for I in range] if i%3 ==0]   # list down sort when g = (I for I in range () if i%3 ==0)   # Generator expression using generator expression when large amount of data Type print (l) print (g) for I in G:print (i)

10. Interview questions

Def demo (): For    I in range (4):        yield Ig=demo () g1= (i-I in G) g2= (I-I in G1) print (list (G1)) (list (G2)) def  Add (n,i):    return N+idef test (): For    I in range (4):        yield ig=test () for n in [1,3,10]:    g= (Add (n,i) for I in g) Print (List (g)) #一个生成器 can only be taken once # The generator never executes when it does not find its value # when he executes, the value of all variables at the time of execution will prevail.

  

Python "Iterator builder list Derivation"

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.