One, iterator
1. What is an iteration? : Iteration is a repeating process, and each repetition is based on the last result
2. Want to know what the iterator is exactly? You must first understand the concept of what is an iterative object?
Objects that can be iterated: in Python, any object with a built-in __iter__ method is an iterative object
Num=1
The following are objects that can be iterated
str1= ' Hello '
list1=[1,2,3]
Tup1= (a)
dic={' x ': 1}
S1={' A ', ' B ', ' C '}
F=open (' A.txt ', ' W ', encoding= ' utf-8 ')
3, Iterators: Iterative value tool, iterative object execution __iter__ method The resulting return value is the iterator object
dic={' x ': 1, ' Y ': 2, ' Z ': 3}
ITER_DIC=DIC.__ITER__ ()
Print (iter_dic.__next__ ())
Print (iter_dic.__next__ ())
S1={' A ', ' B ', ' C '}
ITER_S1=S1.__ITER__ ()
Print (iter_s1.__next__ ())
Print (iter_s1.__next__ ())
list1=[1,2,3]
ITER_LIST1=LIST1.__ITER__ ()
Print (iter_list1.__next__ ())
4. An iterative object vs iterator object?
‘‘‘
Objects that can be iterated: str,list,tuple,dict,set,file
1. How to get an iterative object: No need to get it, Python built-in Str,list,tuple,dict,set,file is an iterative object
2. Features:
The built-in __iter__ method is called an iterative object, and executing the method gets an iterator object
Iterator object: The file object itself is an iterator object
1. How to get an iterator object:
Executes the __iter__ method of an iterative object, and the returned value is the iterator object
2. Features:
Built-in with the __next__ method, executing this method will get a value from the iterator object
There is a built-in __iter__ method that executes this method to get the iterator itself
‘‘‘
x= ' Hello '
ITER_X=X.__ITER__ ()
iter_x.__next__
Print (iter_x.__iter__ (). __iter__ () is iter_x)
The file itself is an iterator object
str1= ' Hello '
list1=[1,2,3]
Tup1= (a)
dic={' x ': 1}
S1={' A ', ' B ', ' C '}
F=open (' A.txt ', ' W ', encoding= ' utf-8 ')
F.__next__ ()
5. Analysis of the advantages and disadvantages of iterators
Advantages of 5.1 iterators:
5.1.1, provides a way to not rely on the index of the value
L=open (' A.txt ', ' R ', encoding= ' utf-8 ')
ITER_L=L.__ITER__ ()
While True:
Try
Print (iter_l.__next__ ())
Except stopiteration:
Break
5.1.2 iterators for more memory savings
Item=range (0,100000000000000000000000000000000000000000000)
Print (item)
Disadvantages of 5.2 iterators:
5.2.1, take value trouble, can only one take, can only take back,
5.2.2, and is disposable, cannot get length with Len
x=[1,2,3]
ITER_X=X.__ITER__ ()
While True:
Try
Print (iter_x.__next__ ())
Except stopiteration:
Break
Print (' second time ================================= ')
ITER_X=X.__ITER__ ()
While True:
Try
Print (iter_x.__next__ ())
Except stopiteration:
Break
6. For loop principle Analysis:
6.1. The For loop is called an iterator loop, and the in followed must be an iterative object
6.2, the For loop executes the __iter__ method of the In object, and gets the iterator object
6.3. Then call the iterator object's __next__ method, get a return value assigned to line, execute a loop body
6.4, cycle, until the value is complete, the for loop will detect an abnormal auto-end loop
L=open (' A.txt ', ' R ', encoding= ' utf-8 ')
For line in L: #iter_l =l.__iter__ ()
Print (line)
For item in {' X ': 1, ' Y ': 2}:
Print (item)
Second, generator
Generator:
In-function packages contain the yield keyword,
Call the function again, will not execute the function body code, get the return value is a generator object
Def chicken ():
Print (' =====>first ')
Yield 1
Print (' =====>sencond ')
Yield 2
Print (' =====>third ')
Yield 3
Obj=chicken ()
Print (obj)
The generator is essentially an iterator, which means that the generator's gameplay is actually an iterator.
Print (obj.__iter__ () is obj)
Res=obj.__next__ ()
Print (RES)
Res1=obj.__next__ ()
Print (RES1)
Res2=obj.__next__ ()
Print (Res2)
Obj.__next__ ()
1, iter_obj=obj.__iter__ (), get the iterator
2, Departure iter_obj.__next__ (), get the return value of the method, assign value to item
3, the cycle, until the function is not in the yield, that is, the value is complete
4. For will detect stopiteration exception, end loop
For item in obj:
Print (item)
Sum yield:
1, provide us with a way to customize the iterator,
You can use the yield keyword within a function, and the result of calling a function is a generator, which is the iterator
2. Yield can be used as a return value, except that return returns only once, and yield can be returned multiple times
Because yield can save the state of the function execution
Def my_range ():
Print (' Start ... ')
N=0
While True:
Yield n
N+=1
Obj=my_range ()
Print (obj)
Print (obj.__next__ ())
Print (obj.__next__ ())
For I in My_Range ():
Print (i)
def my_range (start,stop,step=1):
N=start
While N < stop:
Yield N #yield 4
N+=step #5
Obj=my_range (3,7,2) #3, 5,
Print (obj.__next__ ())
Print (obj.__next__ ())
For item in My_Range (5,10,2):
Print (item)
Iii. expression of yield of generators
Def eat (name):
Print ('%s ready to eat '%name)
Food_list=[]
While True:
Food=yield food_list # food= ' Bones '
Food_list.append (food) #food_list =[' swill ', ' Bones ']
Print ('%s start to eat%s '% (Name,food))
Dog1=eat (' Alex ')
1, must initialize once, let the function stop in the position of yield
Res0=dog1.__next__ ()
Print (RES0)
2, the next thing is to feed the dog
Send has two functions
1. Pass the value to yield
2, the same __next__ function
Res1=dog1.send (' swill ')
Print (RES1)
Res2=dog1.send (' bone ')
Print (Res2)
Res3=dog1.send (' Shit ')
Print (RES3)
IV. process-oriented programming ideas
1 process-oriented programming ideas
The core is the ' process ' word, the process is the steps to solve the problem, that is, what to do first, what to do ....
Process-oriented programming is like designing a pipeline, which is a mechanical way of thinking.
2. Demonstration:
3. Summarize the advantages and disadvantages:
Advantages: Complex problems are streamlined and simplified
Cons: Modify a stage, other stages may need to make changes, reaching, that is, extensibility is very poor
Application: For scenarios with low extensibility requirements
1, Step one: Get the user entered the legitimate information: User name, password, balance, age
Db_path= ' Db.txt '
Def get_uname ():
While True:
Uname=input (' User name >>: '). Strip ()
If not Uname.isalpha ():
Print (' \033[45m username must be English letter ... \033[0m ')
Continue
With open (R '%s '%db_path, ' r ', encoding= ' utf-8 ') as F:
For line in F:
Uinfo=line.strip (' \ n '). Split (', ')
if uname = = Uinfo[0]:
Print (' \033[45m user name already exists ... \033[0m ')
Break
Else
Return uname
Def get_pwd ():
While True:
Pwd1=input (' Please enter password >>: '). Strip ()
Pwd2=input (' re-enter password >>: '). Strip ()
if pwd1 = = Pwd2:
Return PWD1
Else
Print (' \033[45m two input password is inconsistent, please re-enter ... \033[0m ')
Def get_bal ():
While True:
Bal=input (' Please enter balance: '). Strip ()
If Bal.isdigit ():
# Bal=int (BAL)
Return Bal
Else
Print (' \033[45m money must be a number, silly fork ... \033[0m ')
Def get_age ():
Pass
2. Step two: Write the file
def file_hanle (uname,pwd,bal,age):
With open (R '%s '%db_path, ' a ', encoding= ' utf-8 ') as F:
F.write ('%s,%s,%s,%s\n '% (uname,pwd,bal,age))
Registration function
def register ():
#步骤1:
Uname=get_uname () #拿到合法的用户名
Pwd=get_pwd () #拿到合法的密码
Bal=get_bal () #拿到合法的余额
#步骤2:
File_hanle (Uname,pwd,bal) #写入文件
Python tour. Chapter III. function 3.30