Python note-4 (iterator & generator), python note-4
#! /Usr/bin/env python
#-*-Coding: UTF-8 -*-
#1. iterator & Generator
# Generator
# The correct method is to use the for loop, because generator is also an iteratable object:
G = (x * x for x in range (10 ))
For n in g:
Print (n)
# In the Fibonacci series (Fibonacci), any number except the first and second numbers can be obtained by adding the first two numbers:
#1, 1, 2, 3, 5, 8, 13, 21, 34 ,...
# The Fibonacci series cannot be written in the list generation form, but it is easy to print it out using functions:
Def fib (max ):
N, a, B = 0, 0, 1
While n <max:
Print (B)
A, B = B, a + B
N = n + 1
Return 'done'
Print (fib (10 ))
# The above functions and generator are only one step away. To change the fib function to generator, you only need to change print (B) to yield B:
Def fib (max ):
N, a, B = 0, 0, 1
While n <max:
# Print (B)
Yield B
A, B = B, a + B
N + = 1
Return 'done'
# Generator execution
Data = fib (10)
Print (data)
Print (data. _ next __())
Print (data. _ next __())
Print ('Do something else ')
Print (data. _ next __())
Print (data. _ next __())
Print (data. _ next __())
Print (data. _ next __())
Print (data. _ next __())
# After the function is changed to generator, we basically never use next () to obtain the next return value, but directly use the for loop for iteration:
For n in fib (6 ):
Print (n)
# However, when you use a for loop to call generator, the return value of the return Statement of generator cannot be obtained. If you want to get the returned value, you must capture the StopIteration error. The returned value is included in the value of StopIteration:
G = fib (6)
While True:
Try:
X = next (g)
Print ('G: ', x)
Except t StopIteration as e:
Print ('generator return value: done ')
Break
# You can also use yield to implement concurrent operations in the case of a single thread
# C: \ Users \ sony \ PycharmProjects \ s13 \ newprogramming \ yield. py
# Iterator
# We already know that the data types that can directly act on the for loop are as follows:
# One type is set data types, such as list, tuple, dict, set, and str;
# The first type is generator, including the generator and generator function with yield.
# These objects that can directly act on the for loop are collectively referred to as iteration objects: Iterable.
# You can use isinstance () to determine whether an object is an Iterable object:
From collections import Iterable
Print (isinstance ([], Iterable ))
Print (isinstance ({}, Iterable ))
Print (isinstance ('abc', Iterable ))
Print (isinstance (x for x in range (10), Iterable ))
Print (isinstance (100, Iterable ))
# * The object that can be called by the next () function and continuously return the next value is called the Iterator: Iterator.
# You can use isinstance () to determine whether an object is an Iterator object:
From collections import Iterator
Print (isinstance (x for x in range (10), Iterator ))
Print (isinstance ([], Iterator ))
Print (isinstance ({}, Iterator ))
Print (isinstance ('abc', Iterator ))
# Generators are all Iterator objects, but list, dict, and str are Iterable but not Iterator.
# Use the iter () function to convert Iterable, such as list, dict, and str into Iterator:
Print (isinstance (iter ([]), Iterator ))
Print (isinstance (iter (['abc']), Iterator ))
# All objects that can act on the for loop are of the Iterable type;
# All objects that can act on the next () function are of the Iterator type. They represent a sequence of inert computing;
# Set data types such as list, dict, and str are Iterable but not Iterator. However, you can use the iter () function to obtain an Iterator object.
# The for loop of Python is implemented by constantly calling the next () function, for example:
For x in [1, 2, 3, 4, 5]:
Pass
# Equivalent
# First obtain the Iterator object:
It = iter ([1, 2, 3, 4, 5])
# Loop:
While True:
Try:
# Obtain the next value:
X = next (it)
Optional t StopIteration:
# Exit the loop when StopIteration is encountered
Break
# Decorator
Def w1 (func ):
Def inner ():
# Verification 1
# Verification 2
# Verification 3
Return func ()
Return inner
@ W1
Def f1 ():
Print (f1)
@ W1
Def f2 ():
Print (f2)
@ W1
Def f3 ():
Print (f3)
@ W1
Def f4 ():
Print (f4)
After writing this Code (the function is not executed, not executed, or executed), the python interpreter will explain the code from top to bottom. The steps are as follows:
Yes,On the surfaceThe interpreter will only explain the two sentences of code, because the function isBefore being calledThe internal code is not executed.
On the surface, the interpreter will actually execute these two sentences, but there is a large article in the code of @ w1,@ Function nameIt is a syntactic sugar of python.
In the preceding example, @ w1 performs the following operations:
- Run the w1 function., AndFunctionAs a parameter of the w1 function, that is, @ w1 is equivalent to w1 (f1)
Therefore, internal execution will be performed:
Def inner:
# Verification
Return f1 () # func is the parameter, and func is equal to f1
Return inner # return inner, which represents a function rather than an execution function.
Actually, the original f1 function is inserted into another function.
- Return Value of the executed w1 FunctionAssignmentToFunction Name
The Return Value of the w1 function is:
Def inner:
# Verification
Return Original f1 () # Here f1 represents the original f1 Function
Then, assign the return value to f1 again, that is:
New f1 = def inner:
# Verification
Return Original f1 ()
Therefore, when the business department wants to execute the f1 function in the future, it will execute the New f1 function. In the new f1 function, it will first perform verification before executing the original f1 function, then, the return value of the original f1 function is returned to the business caller.
In this way, the verification function is executed, the content of the original f1 function is executed, and the return value of the original f1 function is returned to the service