1. For loop in Python
for inch [1,2,3,4]:
2. Iterative and iterative protocols
iterable: An iterative, repeatable, iterative
Iterative: In general, it can be used for loops, such as String (str), list, tuple (tuple), dictionary (Dict), collection (set), range, map, filter, enumerate, and so on.
Iterative---iterators: remove elements from a data set
The definition of an iterative protocol: The _iter_ method is implemented internally
Can be iterated for the for loop, there must be a _iter_ method inside
Iterator: iterators, iterators
_next_ method: is a value
Iterators follow an iterator protocol: you must have the _iter_ method and the _next_ method
l=[1,2,3,4]a=l.__iter__ () while True: try: x=a.__next__ () print (x) except stopiteration: Break
First Knowledge generator
The generators provided in Python
1, Generator function: Return the result with yield statement, a wipe returns a result
2, generator expression similar to the list pushed, the generator returns an object that produces a result, not a list of results at a time
3. Generator Generator
The essence is the iterator (with the _iter_ method and the _next_ method)
4. Generator even function
import Timedef Genrator_func (): a=1Print ('defines the A variable') yielda B=2Print ('defines a B variable') yieldBG=Genrator_func () print ('g:', G) #打印g可以发现g就是一个生成器print ('_'* -) #分割线print (Next (g)) Time.sleep (1) #sleep一秒看清执行过程print (Next (g))
Generator function Two
# def func (): # #生产衣服 # forIinchRange2000000):# yield#生产了第%s pieces of clothing%i# func1=func () # Print (func1.__next__ ()) #要一件衣服 # Print (func1.__next__ ()) #再买一件衣服 # Print (func1.__next__ ()) #再要买一件衣服 # num =0# forIinchfunc1: #要一批衣服 # print (1) # num+=1# ifnum = =5:# Break
More application
# import time# def tail (filename): # f=open (FileName) # F.seek (0,2) #从文件末尾算起 # whiletrue:# Line=F.readline () #读取文件新的文本行 #ifNot line:# Time.sleep (0.1)# Continue# yieldline# Tail_g=tail ('tmp')# forLineinchtail_g:# Print (line)
Calculate moving Averages
def Averager (): Total =0.0 count =0 average =none while true:term =yield average total +=term count +=1 average = Total/count g_avg =averager () Next (g_avg) print (G_avg.send ( 10 30 5 ))
The adorner for calculating the moving average-pre-excitation association
def Time (func): Def inner (*args,**Kwargs): Ret=func (*args,**Kwargs) Next (ret)returnretreturninner@timedef Averager (): Total=0.0Ccount=0Average=None whileTrue:term=yieldaverage Total+=Term ccount+=1Average=total/Ccountg_avg=Averager () print (G_avg.send (Ten)) Print (G_avg.send ( -)) Print (G_avg.send (5))
Yiel from
def gen1 (): forCinch 'AB': yieldC forIinchRange3): yieldiprint (List (Gen1 ())) def Gen2 ():yield from 'AB' yield fromRange3) Print (List (Gen2 ()))
Liebiao Derivation and generator expressions
egg_list=[' egg%s' for in range ' #列表解析laomuji = (' egg%s' for in range) # Generator expression print (Laomuji) print (Next (Laomuji)) #next本质就是调用_next_print (laomuji.__next__ ()) print (Next (Laomuji))
Summary of this chapter
Objects that can be iterated:
Have _iter_ methods such as: Range (), str, list, tuple, dict, set
Properties: Lazy Operation
Iterators: Iterator:
There are _iter_ methods and _next_ methods such as: ITER (Range ()), ITER (str), ITER (list), ITER (tuple), ITER (set), Reversed (list_o), map (func,list_ O), filter (func,list_o), File-o
Generator generator:
Essence: iterators, so have __iter__ methods and __next__ methods
Features: Lazy operation, developer Customization
Advantages of using Generators:
1. Delay the calculation and return one result at a time. That is, it does not produce all the results at once, which is useful for large data processing.
#The list resolves sum ([iFor IIn range (100000000)])#Large memory footprint, machine easy to get stuck#Generator expression sum (I for i in Range (100000000))# hardly takes up memory
Python----iterators and generators