Directory
- Iterators & Generators
- Decorative Device
- Json & Pickle Data serialization
- Software Catalog Structure specification
- Jobs: ATM Project development
1. List generation, Iterators & Generator list generation
List generation is a very powerful expression built into Python that generates a list.
Now there is a need to look at the list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] and I ask you to add 1 to each value in the table, how do you do that?
1>>>a2[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]3>>> B = []4>>> forIinchA:b.append (i+1)5 ... 6>>>b7[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]8>>> A =b9>>>aTen[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Normal Youth Edition
1>>>a2[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]3>>> A = map (LambdaX:x+1, a)4>>>a5<map Object at 0x101d2c630>6>>> forIinchA:Print(i)7 ... 8293Ten4 One5 A6 -7 -8 the9 -10 -11
Literary Youth Edition
1 for in range2 >>> a3 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Forced Youth Edition
This is called list generation
Generator
With list generation, we can create a list directly. However, with memory limitations, the list capacity is certainly limited. Also, creating a list of 1 million elements takes up a lot of storage space, and if we just need to access the first few elements, the vast majority of the space behind it is wasted.
So, if the list element can be calculated according to an algorithm, can we continue to calculate the subsequent elements in the process of the loop? This eliminates the need to create a complete list, which saves a lot of space. In Python, this side loop computes the mechanism, called the generator: Generator.
There are a number of ways to create a generator. The first method is simple, as long as a list of the generated formula is []
changed ()
to create a generator:
>>> L = [x * x for x in range]]>>> l[0, 1, 4, 9, N, F, $, $, 81]>>> g = (x * x for X In range (+) >>> G<generator object <genexpr> at 0x1022ef630>
The L
difference between creating and making is g
only the outermost []
and, a ()
L
list, and g
a generator.
We can print out every element of the list directly, but how do we print out every element of generator?
If you want to print out one, you can next()
get the next return value for generator by using a function:
>>> Next (g) 0>>> next (g) 1>>> next (g) 4>>> next (g) 9>>> next (g) 16>> > Next (g) 25>>> next (g) 36 ...
We have said that generator saves the algorithm, each time it is called next(g)
, computes g
the value of the next element until the last element is computed, and when there are no more elements, the error is thrown StopIteration
.
Of course, this constant invocation is next(g)
so perverted that the correct approach is to use for
loops, because generator is also an iterative object:
>>> g = (x * x for x in range) >>> for n in G: ... Print (n) ... 0149162536496481
So, after we create a generator, we basically never call next()
it, but iterate over it through the for
loop and don't need to be concerned about StopIteration
the error.
Generator is very powerful. If the calculated algorithm is more complex, and the loop with similar list generation for
cannot be implemented, it can also be implemented with functions.
For example, the famous Fibonacci sequence (Fibonacci), except for 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:
def fib (max): N, a, b = 0, 0, 1 while n < max: print (b) A, B = B, a + b n = n + 1 return ' do Ne
Note that the assignment statement:
A, B = B, A + b
Equivalent:
t = (b, A + b) # T is a Tuplea = T[0]b = T[1]
However, you do not have to explicitly write out a temporary variable T to assign a value.
The above function can output the number of the first n of the Fibonacci sequence:
>>> fib (11235813213455done)
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:
EF FIB (max): n,a,b = 0,0,1 while n < max: #print (b) yield B, a = b,a+b n + = 1
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:
>>> f = fib (6) >>> F<generator object fib at 0x104feaaa0>
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
.
data = fib (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__ ()) #输出 <generator object fib at 0x101be02b0>11, do something else. 235813
在上面fib
example, we continue to call in the loop process yield
, will continue to interrupt. Of course, you have to set a condition for the loop to exit the loop, or it will produce an infinite sequence.
Similarly, after changing a function to generator, we basically never use it next()
to get the next return value, but instead use the for
loop directly to iterate:
>>> for N in fib (6): ... Print (n) ... 112358
However for
, when calling generator with a loop, the return value of the statement that is not generator is found return
. If you want to get the return value, you must catch the StopIteration
error, and the return value is included in StopIteration
the value
:
>>> g = fib (6) >>> while True: ... Try: ... x = Next (g) ... Print (' G: ', x) ... Except Stopiteration as E: ... Print (' Generator return value: ', E.value) ... Break...g:1g:1g:2g:3g:5g:8generator return Value:done
The effect of concurrency can also be achieved in single-threaded case with yield
#_ *_coding:utf-8_*___author__ = ' Alex Li ' import timedef Consumer (name): print ("%s ready to eat Buns!"%name) while true:< C2/>baozi = yield print ("Bun [%s] came, was [%s] eaten!"% (Baozi,name)) def producer (name): C = Consumer (' A ') C2 = Consumer (' B ') c.__next__ () c2.__next__ () print ("Lao Tzu began to prepare buns!") For I in range: time.sleep (1) print ("Made 2 buns!") C.send (i) c2.send (i) producer ("Alex")
Iterators
We already know that for
there are several types of data that can be directly acting on a loop:
A class is a collection of data types, such as,,, list
tuple
, and dict
set
str
so on;
One is generator
to include the generator and yield
the generator function with the band.
These objects, which can be directly applied to for
the loop, are called iterative objects: Iterable
.
You can use to isinstance()
determine whether an object is an Iterable
object:
>>> from Collections Import iterable>>> isinstance ([], iterable) true>>> isinstance ({}, iterable) true>>> isinstance (' abc ', iterable) true>>> isinstance ((x for X in range), iterable) True >>> isinstance (iterable) False
The generator can not only be used for for
loops, but it can also be next()
called by the function and return the next value until the last throw StopIteration
error indicates that the next value cannot continue to be returned.
* An object that can be called by next()
a function and continually returns the next value is Iterator
called an iterator:.
You can use to isinstance()
determine whether an object is an Iterator
object:
>>> from Collections Import iterator>>> isinstance ((x to X in range), Iterator) true>>> are Instance ([], Iterator) false>>> isinstance ({}, Iterator) false>>> isinstance (' abc ', Iterator) False
Generators are Iterator
objects, but,, list
dict
str
Though Iterable
they are, they are not Iterator
.
Turn list
, dict
and str
wait for the Iterable
Iterator
function to be used iter()
:
>>> Isinstance (ITER ([]), Iterator) true>>> isinstance (ITER (' abc '), Iterator) True
Summary
Any object that can be used for for
the loop is a Iterable
type;
All objects that can be used for next()
functions are Iterator
types, which represent a sequence of lazy computations;
Collection data types such as list
, dict
,, and str
so on are Iterable
not Iterator
, however, you can iter()
get an object from a function Iterator
.
The Python for
loop is essentially implemented by calling next()
functions, such as:
For x in [1, 2, 3, 4, 5]: Pass
2. Decorative Device
3.JSON and Pickle Data serialization
python-Base Generation Builder iterator JSON Pickl