Today we learned about iterator generators and built-in functions and anonymous functions, and to tell you the truth, there are some difficulties.
First, iterators and generators
1, how to take the value from the list, dictionary:
Index indexes
For loop
All the values that can be used for a loop are iterated
(1) Iterative protocol: Internally containing __iter__ methods are iterative
(2) Iterator protocol: Internally containing the __iter__ method and the __next__ method are iterators
What is iterative: internally containing __iter__ methods are iterative
What is an iterator: iterator =iter (iterative) with a __next__ method
The biggest benefit of iteration: saving memory
Range in Py2 generates a list regardless of range, which will be used to store all values
Range in Py3 does not actually generate any value, regardless of range
To determine whether an iterator can be iterated or not:
From collections Import Iterable,iterator
Print (range (10000))
Print (Isinstance (range 10000), iterable) is an iterative
Print (Isinstance (range (10000), Iterator)) is an iterator
Benefits of Iterators:
Save Memory
Go to a value to do the next calculation, and do not have to wait until all the values are calculated to start the next operation-fast
Characteristics of iterators: lazy operations
2. Generator (Generator)
The iterator you write is a generator
Two mechanisms for writing your own generator (iterator): generator function, generator expression
(1) Generator function:
def cloth_g (num):
For I in range (num):
Yield ' cloth%s '%i
g = cloth_g (100)
Print (Next (g))
Print (Next (g))
A function with yield is a generator function.
Yiled record the current location, wait for next next to trigger the state of the function
The call to the generator function does not trigger execution of the code, but instead returns a generator (iterator)
If you want the generator function to execute, you need to use next.
Example of using the generator to listen for file input
Import time
Def listen_file ():
With open (' file ') as F:
While True:
line = F.readline ()
If Line.strip ():
Yield Line.strip ()
Time.sleep (0.1)
g = Listen_file ()
For line in G:
Print (line)
Send keyword: passes a parameter to the inside of the generator function during next execution
To pass a value in the generator, there is an activation process, and the first time you must use next to trigger the generator
How to take a value from the generator
(1) Next can be stopped at any time, the last one will be an error
(2) The For loop is traversed from beginning to end, no break is encountered, return does not stop
(3) A strong turn of the list tuple data type will load all the data into memory, wasting memory
The generator function is one of the ways that our Python programmers implement the iteration
The main feature is that the yield is included in the function
Calling a generator function will not execute the code in this function, only get a generator (iterator)
The code inside the function executes only when the value is taken from the generator, and every data fetch is executed to get the data code.
Ways to get data include next, send loops, data type conversions
Yield returns a simple way to return a value, if it is an iteration of the loop itself, and to return each element in the iterated data, you can use yield from
When using send, pre-excitation is required after the generator is created, which can be done using adorners
Generator features: Memory saving, lazy operation
Generators are used to solve the decoupling between memory problems and program functions
3, generator expression, use generator expression when large amount of data
List = (Out_exp_res for out_exp in input_list if out_exp = = 2)
List derivation, sort by
List = [Out_exp_res for out_exp in input_list if out_exp = = 2]
Out_exp_res: List-generated element expression, which can be a function with a return value
For Out_exp in input_list: Iteration input_list out_exp incoming out_exp_res expression
if out_exp = = 2: Filters which values can be returned based on conditions
(1) A generator can only be evaluated once
(2) The generator never executes when it is not looking for a value
(3) When he executes, the value of all variables at the time of execution shall prevail.
Second, built-in functions and anonymous functions
1. Built-in function:
Callable (o), O is the parameter to see if this variable is callable. O is the function name returned ture
Dir () View all names owned by a variable lock
Bin (): Binary, Oct () octal, Hex () hex
ABS (): Calculate absolute value
Divmod (): Quotient and remainder (quotient remainder function)
Enumerate (): Index of the display element
Eval (): Extract execution
Pow (): Pow (2,3,3) # (2**3)%3 2 three-time redundancy
Reversed (): Reverse list output
. Sort (): Sorted in ascending order
Round (): Default rounding, decimal precision, rounding
__import__: Through the string guide module
ID (o) o is a parameter that returns the memory address of a variable
Hash (o) O is a parameter that returns a hash value of a hash variable, and the non-hash variable will be hashed after the error.
SUM (): Sum operation
Min (): Calculates the minimum value
Max (): Calculates the maximum value
Print (Ord (' a ')) enter the character to find the location of the character encoding A-Z 97+26
Print (Chr (97)) Enter position number to find its corresponding character A-Z 65+26
ASCII: is the return value in ASCII code, not the return/U
Format (' Print element ', ' <20 '):< left-aligned,> right-aligned, ^ center-aligned
REPR (): Returns the string form of an object (the true Colours)
Enumerate: Enumeration receives two parameters: one container type, one ordinal starting value
All (): Can iterate over objects, all ture is ture
Any (): An iterative object, one ture is ture
For I in Zip (): A function is used to take an iterative object as an argument, to wrap the corresponding element in the object into a tuple, and then return a list of those tuples, the same length as the shortest
Print (self, *args, sep= ", end= ' \ n ', file=none,flush=t/f)
File: Default output to screen, if set to file handle, output to file
Sep: Print separators between multiple values, default to Spaces
End: The end of each print, the default is the line break
Flush: Output content to stream file immediately, not cached
Hash hashes
(1) A hash of the hash data type will be given a number
(2) During the execution of a program, the result is always the same as the hash of the same hash variable.
(3) After the execution of a program, the result is almost always different after the hash variable hashes.
(4) The underlying storage of the hash dictionary and the de-weight mechanism of set set are all related
Filter (): Filtering elements
map:def func (num):
Return num * * 2
For I in Map (func,range):p rint (i)
Sorted (l,key= ...): sort
2. anonymous function
Lambda: anonymous function keyword: functional name = LAMBDA parameter: return value
calc< function Name > = lambda< define anonymous functions keyword > n< parameter >:n**n< return value >
Print (Calc (10))
Third, recursive invocation:
1, recursive call in the process of invoking a function, directly or indirectly called the function itself, called a recursive call
Recursive Prerequisites Two stages: 1, recursive 2, backtracking
2. Recursive invocation must have a definite end condition
3, each time into a deeper level of recursion, the problem size should be reduced compared to the last recursion
4, recursive efficiency is not high
Modify recursive maximum depth
Import Sys
Print (Sys.setrecursionlimit (1000))
Four or two-point method
L = [18,22,26,30,32,35,41,42,43,55,56,66,67,69,72,76,82,83,88]
def func (L,num):
MID = Len (l)//2 #中间截取
If num > L[mid]: #判断所传数字是否大于mid
Func (l[(mid) +1:],num) #大于从中间往后找
Elif num < L[mid]: #判断所传数字是否小于mid
Func (l[0: (mid)],num) #大于从中间往前找
Else:print (' Find it ')
Func (l,66)
Python iterator generator and built-in functions, anonymous functions