1 Generator (Variation of Function)
Judging whether a function is a generator function: Just see if there is yield inside the function
# Generator function (whether yield is included in it) def func(): print('F1') yield 1 print('F2') yield 2 print('F3') yield 100 print('F4') # The internal code of the yield function does not execute and returns a generator object. v1 = func() # Generators can be for loops, and once the loops start, the internal code of the function begins to execute. for item in v1: print(item)
Circulation process:
-
- The for loop starts the first loop, first executes the code in front of the yield, then returns the value of the yield to item and stops the first loop when the yield is executed.
- Second loop: Start executing the code after the yield of the last loop. When the second yield (yield2) is executed, return the value of yield2 to item and stop the second loop.
- The loop terminates automatically until all yield s are completed
def func(): count = 1 while True: yield count count += 1 val = func() for item in val: print(item)
Summary: If yield exists in a function, then the function is a generator function. Calling the generator function will return a generator. Only when the generator is for loop, the code inside the generator function will be executed. Each loop will get the value returned by yield.
def func(): count = 1 while True: yield count count += 1 if count == 100: return val = func() for item in val: print(item)
Example: Reading files
def func(): """ //Read the contents of the file in batches and return the contents of the file to the caller. :return: """ cursor = 0 while True: f = open('db', 'r', encoding='utf-8')# redis over a network connection # Pronoun redis[0:10] f.seek(cursor) data_list =[] for i in range(10): line = f.readline() if not line: return data_list.append(line) cursor = f.tell() f.close() # Close the connection to redis for row in data_list: yield row for item in func(): print(item)
redis source code example
Generator role:
Generate data
-
It is a special iterator.
def func(): yield 1 yield 2 yield 3 v = func() result = v.__next__() print(result) result = v.__next__() print(result) result = v.__next__() print(result) result = v.__next__() print(result)
-
It is also a special iterative object.
def func(): yield 1 v = func() result = v.__iter__() print(result)
Other knowledge:
-
yeild from keyword (from a little bit of xxx)
def base(): yield 88 yield 99 def func(): yield 1 yield 2 yield from base() # Get a little bit from base() yield 3 result = func() for item in result: print(item)
send method of generator
def func(): print(123) n = yield 'aaa' print('-->',n) yield 'bbb' g = func() print(g) n = next(g) print(n) print('-'*20) next(g) # g.send('uysdfhfoiusyg') acts as next(g)
Be careful:
1. Generator takes one time and no more, and takes another time when the interior is empty.
-
2. Lazy Operations: Do Not Take or Do Not Execute
ret = filter(lambda n:n%3==0,range(10)) # ret is an iterator print(len(list(ret))) # 4 # list(ret) = [0,3,6,9] print(len(list(ret))) # 0 # list(ret) = []
2 Derivative Formula
2.1 List Derivation
-
1. Purpose
Easy to generate a list
-
2. Basic format
Variable= [for loop variable for loop is an iterative object]
v1 = [i for i in iterative object]
v2 = [i for i in iterative object if condition] append only when condition is true-
Practice
v1 = [ i for i in 'alex' ] # ['a','l','e','x'] v2 = [i+100 for i in range(10)] # [100,101,102,103,104,105,106,107,108,109] v3 = [99 if i>5 else 66 for i in range(10)] # [66,66,66,66,66,66,99,99,99,99] def func(): return 100 v4 = [func for i in range(10)] # [func,func,func,func,func,func,func,func,func,func,] v5 = [lambda : 100 for i in range(10)] # [lambda : 100,lambda : 100,lambda : 100,lambda : 100,lambda : 100,lambda : 100,lambda : 100,lambda : 100,lambda : 100,lambda : 100] result = v5[9]() # 100 v6 = [lambda :i for i in range(10)] # [lambda :i,lambda :i,lambda :i,lambda :i,lambda :i,lambda :i,lambda :i,lambda :i,lambda :i,lambda :i,] result = v6[5]() # 9 v7 = [lambda x:x*i for i in range(10)] # 1. What is v7? v7 = [lambda x:x*i,lambda x:x*i,lambda x:x*i,lambda x:x*i,lambda x:x*i,lambda x:x*i,lambda x:x*i,lambda x:x*i,lambda x:x*i,lambda x:x*i,] # 2. What is the result of v7[0](2)? v7[0](2) = 18 def num(): return [lambda x:i*x for i in range(4)] # Num () - > [function, function, function] print([ m(2) for m in num() ]) # [6,6,6,6] # ##################### screen ######################### v8 = [i for i in range(10) if i > 5] # [6,7,8,9]
2.2 Set Derivation Formula
-
1. Purpose
Convenient generation of a collection
-
2. Basic format
Variable= {for loop variable for loop is an iterative object}
-
V1 = {i for I in iteratable object}
V2 = {i for I in iterative object if condition} # append only when condition is truev1 = { i for i in 'alex' } # {'a','l','e','x'}
2.3 Dictionary Derivation
-
1. Purpose
Convenient generation of a dictionary
-
2. Basic format
v1 = { 'k'+str(i):i for i in range(10) } #{'K0':0,'K1':1,'K2':2,'K3':3,'K4':4,'K5':5,'K6':6,'K7':7,'K8':8,'k9':9} v1 = { 'k':i for i in range(10) } # {'k':9} #If a dictionary key exists, the new value overrides the old value, and if it does not exist, it is updated.
2.4 Generator Derivation
# def func(): # result = [] # for i in range(10): # result.append(i) # return result # v1 = func() v1 = [i for i in range(10)] # List derivation, which immediately creates all elements in a loop. print(v1) # def func(): # for i in range(10): # yield i # v2 = func() v2 = (i for i in range(10)) # Generator derivation, creating a generator, internal loop for execution.
# Example 1 def func(): result = [] for i in range(10): result.append(i) return result v1 = func() for item in v1: print(item) # Example 2 def func(): for i in range(10): def f(): return i yield f v1 = func() for item in v1: print(item()) # Example 3: v1 = [i for i in range(10)] # List derivation, which immediately creates all elements in a loop. v2 = (lambda :i for i in range(10)) for item in v2: print(item())
3 Recursion
Recursion is the function calling itself (disadvantage: inefficient)
The default maximum number of recursions supported by python is 1000
def func(): print(1) func() func()
def func(i): print(i) func(i+1) func(1)
def func(a,b): # Fibonacci can only recurse 1000 times # 1 # 1 # 2 # 3 # 5 print(b) func(b,a+b) func(0,1)
def func(a): if a == 5: return 100000 result = func(a+1) + 10 return result v = func(1)
# Recursive return value def func(a): if a == 5: return 100000 result = func(a+1) + 10 v = func(1) name = 'alex' def func(): def inner(): print(name) return inner v =func()