I am really ignorant of programming language ... Today, I saw Liaoche's teacher about iterations, iterators, generators, recursion, and so on, word day, what's this all about?
1. About iterations
Given a list or tuple, we can iterate through for the list or tuple through a loop, which we call Iteration (iteration) (the Chinese meaning of iteration is: repetition, repetition, iteration, etc.). The objects traversed by these for loops (list or tuple, etc.) become iterative objects (iterable).
In other words, an "iteration" is an action or a process that checks the elements of a list or tuple one at a time (traversal). As follows:
1 for in range (0,10):2 print (i)
The result would be 0 1 2 3 4 5 6 7 8 9 This process is iterative, and the range (0,10) Here is an iterative object (iterable). So, when we use for a loop, the loop works as long as it works on an iterative object, for and we don't care much about whether the object is a list or another data type.
1.1 To determine whether an object is an iterative object
Judging by the iterable type of the collections module:
1 >>>from collections import iterable 2 >>>isinstance ( " ABC Span style= "COLOR: #800000", ", iterable) # Whether STR ' ABC ' Can Iterate (iterable) 3 " Span style= "COLOR: #008080" >4 >>>isinstance ([1,2,3],iterable) # list [[] "can iterate (iterable) 5 Span style= "COLOR: #000000" "True 6 >>>isinstance (123,iterable) # integer 123 to iterate
2. Generator
In Python, a mechanism that loops one side of the computation, called the generator: Generator. There are two ways of defining generator.
2.1 First method of defining generator
1 for in range (ten)]2 >>> L3 [0, 1, 4, 9, +,- C10>4 for in range5 >>> g6 <generator Object <genexpr> at 0x1022ef630>
This is a simple method of changing a list generation [] to () and creating a generator. The difference created here is L g only the outermost and is [] a () L list, and g it is a generator. If you want to print out an element in G, you can next() get the next return value for generator by using the function:
1>>>Next (g)2 03>>>Next (g)415>>>Next (g)647>>>Next (g)899>>>Next (g)Ten16 One>>>Next (g) A25 ->>>Next (g) -36 the>>>Next (g) -49 ->>>Next (g) -64 +>>>Next (g) -81 +>>>Next (g) A Traceback (most recent): atFile"<stdin>", Line 1,inch<module> -Stopiteration
Generator saves the algorithm, each time it is called next(g) , computes g the value of the next element until it is calculated to the last element, no more elements are thrown when the StopIteration error occurs. However, after we have created a generator, we will basically never invoke next() it, but iterate over for it by looping:
1>>> g = (x * x forXinchRange (10))2>>> forNinchg:3...Print(n)4 ... 5 0617489916Ten25 One36 A49 -64 -81
2.1 The second method of defining generator
The second method is defined by a function.
The famous Fibonacci sequence (Fibonacci), in addition to the first and second numbers, can be summed up by the top two numbers:
1, 1, 2, 3, 5, 8, 13, 21, 34, ...
The Fibonacci sequence is not written in a list, but it is easy to print it out with a function:
1 def fib (max): 2 N, a, b = 0, 0, 13 while n < Max:4 print(b)5 # this refers to A=b,b=a+b6 n = n + 17 return ' Done '
I now know why to add a max parameter, using N<max to make the a+b number equal to the input max, such as FIB (10), then the end loop is a+b exactly 10 times.
The test code is as follows:
FIB (6):112358'done'
Looking closely, it can be seen that the fib function is actually a calculation rule that defines the Fibonacci sequence, which can be derived from the first element, and the subsequent arbitrary elements, which are actually very similar to generator.
In other words, the above functions and generator are only a step away. To turn fib a function into a generator, just print(b) change yield b it to:
1 def fib (max): 2 N, a, b = 0, 0, 13 while n < Max:4 yield b5
A, B = B, A + b6 n = n + 17 return'done< /c22>'
This is another way to define generator. If a function definition contains a yield keyword, then the function is no longer a normal function, but a generator.
1 >>> f = fib (6)2 >>> F3 <generator object fib at 0x104 Feaaa0>
After changing the function to generator, we basically never use it next() to get the next return value, but instead use the for loop to iterate:
1 for in fib (6):2 ... Print (n) 3 ... 4 15 16 27 38 59 8
The most difficult thing to understand here is that the generator is not the same as the execution flow of the function. The function is executed sequentially, the statement is encountered return or the last line of the function is returned. The function that becomes generator, executes at each invocation next() , encounters a yield statement return, and executes again from the last statement returned yield .
Let's look at the following example:
1 defOdd ():2 Print('Step 1')3 yield14 Print('Step 2')5 yield(3)6 Print('Step 3')7 yield(5)
when you call the generator, you first generate a generator object , and then you next() continue to get the next return value with the function:
1>>> o =Odd ()2>>>Next (O)3Step 1415>>>Next (O)6Step 2738>>>Next (O)9Step 3Ten5 One>>>Next (O) A Traceback (most recent): -File"<stdin>", Line 1,inch<module> -Stopiteration
As you can see, odd it is not a normal function, but a generator, which is yield interrupted during execution and continues execution the next time. after executing 3 times yield , it has not been yield able to execute, so the 4th call will be an next(o) error.
iterations, generators, and so on in Python