Slice (found some new action)
Reference Links: https://www.liaoxuefeng.com/wiki/1016959663602400/1017269965565856
Spacer elements having
>>> L = [i for i in range (20)] of all numbers, each take a two >>> Ll = L [:: 2] >>> Ll [0, 2,. 4,. 6,. 8, 10 , 12, 14, 16, 18] before the number 10, each take a two
It can be used to take all the elements for replication
>>> L[:] [0, 1, 2, 3, ..., 99]
Iteration
Reference Links: https://www.liaoxuefeng.com/wiki/1016959663602400/1017316949097888
How to determine an object is iterable it? It is determined by the type Iterable collections module:
Collections from the Iterable Import >>> >>> the isinstance ( 'ABC', the Iterable) whether the iteration # STR True >>> the isinstance ([l, 2,3], the Iterable) # List whether the iteration True >>> the isinstance ( 123, Iterable) # integer whether iteration False
If you want a list of the index cycle, enumerate () function can be provided by the Python index into the list - the element pair, so that the index can be simultaneously and iterate over the elements
>>> for i, value in enumerate(['A', 'B', 'C']): ... print(i, value) ... 0 A 1 B 2 C
List of Formula
Reference Links: https://www.liaoxuefeng.com/wiki/1016959663602400/1017317609699776
Two cycles may be used, for example, to generate a full array
>>> m = [x + y for x in 'ABC' for y in 'XYZ'] # used to separate spaces between two cycles, try to imagine the following x, y how to use it again for loop outside, and also changes >>> m [ 'AX', 'AY', 'AZ', 'BX', 'BY', 'the BZ', 'the CX', 'CY', 'the CZ'] >>>
Builder
Reference Links: https://www.liaoxuefeng.com/wiki/1016959663602400/1017318207388128
Generator side is calculated, while generating procedural mechanism, for example, we need access to a collection contains a large number of elements (in the mathematical sense, not some kind of data structure), but each time only visit a few of them data, if you use the list to store, will not only take up much storage space, but each time only visit a few of them will cause a great waste
So if these elements can be extrapolated according to some algorithm, it can be recycled continuously calculate the elements behind this mechanism is the generator ( Generator)
To create a generator, there are many ways, the easiest way is to generate a list of type [], replace ()
>>> g=(i for i in range(10)) >>> g <generator object <genexpr> at 0x000001A1CD703518> >>>
Get generator element
If an element to be a builder acquisition, we can next () method
>>> next(g) 0 >>> next(g) 1 pass >>>next(g) 9 >>> next(g) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
Save generator is the algorithm, each call to next (), we calculate a value of the element, the time until the calculated to the last element, no more elements, throws StopIteration error
Of course, this constant invocation above next(g)
is too sick, the correct approach is to use a for
loop because the generator is iterable:
Next >>> (g) Traceback (MOST Recent Last Call): File "<stdin>", Line. 1, in <Module1> the StopIteration >>> for I in g: # Note that because the front of the generator g has iterated over Therefore there will not be any output value, to re-create ... Print (I) ... # recreate >>> I for in G: ... Print (I) ... 0 . 1 2 . 3 . 4 . 5 . 6 7 8 9 >>>
So, we created after a generator, basically never called next()
, but through for
to the iterative loop it, and do not care about StopIteration
the error.
generator is very powerful. If the projection algorithm is complex, with a similar type of list generation for
time cycle can not be achieved, it can also be implemented as a function.
For example, the number of columns known Feibolaqi (the Fibonacci), except for the first and second number, any number can be obtained by the first two numbers together:
1, 1, 2, 3, 5, 8, 13, 21, 34, ...
Feibolaqi formula list by the number of columns to write, however, a function is very easy to print it out:
def fib(max): n, a, b = 0, 0, 1 while n < max: print(b,end=' ') a, b = b, a + b n = n + 1 return 'OK!'
Try to think about the value here a, b = b, a + bb end up with the assignment a + b, or pre-assigned a plus b do, here is the equivalent of an assignment statement
t = (b, a + b ) # t is a tuple # Therefore, before the assignment A A = T [0] B T = [. 1]
The above function may be output before the Fibonacci number N of the Fibonacci series:
>>> fib(6) 1 1 2 3 5 8 'done'
Careful observation, it can be seen, fib
the function is actually defined rules Feibolaqi estimated number of columns may be started from the first element, calculate subsequent optional element, this logic is actually very similar to the generator.
In other words, the above function generator and a stone's throw. Should fib
function becomes a generator, just need to print(b)
read yield b
it:
DEF FIB (max): n-, A, B = 0, 0,. 1 the while n-<max: the yield B # longer required each time the print (i.e., use) where A, B = B, A + B n-= n-+. 1 return 'done'
This is the definition of another method generator. If a function definition contains yield
the keyword, then this function is no longer an ordinary function, but a generator:
>>> f = fib(6) >>> f <generator object fib at 0x104feaaa0>
And execution flow generator function is not the same
Function is executed sequentially, when faced with the return statement returns, but becomes a function generator, and then each time the next call () Executes once encountered yield statement returns the next time next () when it is from at last yield return statement continues
Here is a simple example, the definition of a generator, in turn returns the number 1,3,5: # Note again has three functions yield statement, that next () does not necessarily perform all of the functions once again statements
def odd(): print('step 1') yield 1 print('step 2') yield(3) print('step 3') yield(5)
When calling the generator, first generate a generator object, then next()
the function continues to obtain a return value is:
>>> o = odd() >>> next(o) step 1 1 >>> next(o) step 2 3 >>> next(o) step 3 5 >>> next(o) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
You can see, odd
it is not an ordinary function, but the generator, in the implementation process, encounter yield
is interrupted, the next time to continue. Execution three times yield
, the group has not yield
be implemented, so the 4th call next(o)
on the error.
Back to the fib
example, we continue to call in the cycle yield
, it will continue to be interrupted. Of course, the cycle is set to give a condition to exit the loop, otherwise it will generate an infinite number listed.
Similarly, after the function into a generator, we basically never used next()
to get the next return value, but direct use of for
loop iterations:
>>> for n in fib(6): ... print(n) ... 1 1 2 3 5 8
But by for
the time the cycle is called generator, the generator was found not get the return
statement of the return value. If you want to get the return value, you must capture StopIteration
the error, the return value is contained in StopIteration
the value
middle:
>>> g = fib(6) >>> while True: ... try: ... x = next(g) ... print('g:', x) ... except StopIteration as e: ... print('Generator return value:', e.value) ... break ... g: 1 g: 1 g: 2 g: 3 g: 5 g: 8 Generator return value: done
Iterator
Generator may use the next () to get the next data, the next () determines whether the flag is not a generator, through the next () to get the next value, is a standard iterator (Iterator) a blog, generating It is a side loop mechanism while computing.
Iterables (iterable)
Acting on the object may be referred to as an iterative loop for an object, comprising:
A class is a collection of data types: The List, tuble, dict, set, str like;
One is the generator, comprising a generator and a generator function with a yield of
You can use the isinstance () to determine whether an object is an object Iterable
Iterator (iterator)
May be next () call to return and continue to the next value of an object called an iterator: Iterator
You can also use the isinstance () to determine whether an object is an object iterator
>>> from collections import Iterator >>> isinstance(a,Iterator) True >>>
Builder is Iterator
an object, but list
, dict
, str
though Iterable
, is not Iterator
.
The list
, dict
, str
etc. Iterable
become Iterator
can use the iter()
function:
>>> isinstance(iter([]), Iterator) True >>> isinstance(iter('abc'), Iterator) True
Why list
, dict
, str
and other data types are not Iterator
?
This is because Python is Iterator
an object representation of the data stream, Iterator objects can be next()
invoked continue to function and returns the next data until the absence of data thrown StopIteration
error. This data stream can be seen as an ordered sequence, but we can not know in advance the length of the sequence , can only continue through the next()
realization of next-demand computing a data function, so the Iterator
calculations are inert, only need to return the next data it will be calculated.
Iterator
Even represent an infinite stream of data, such as all natural numbers. The list is never stored using all natural numbers.
Who can act on for
circulating objects are Iterable
type;
Who can act on the next()
function objects are Iterator
types, which represents a sequence of lazy evaluation;
A set of data types, such as list
, dict
, str
and the like are Iterable
, but not Iterator
, however, can iter()
obtain a function Iterator
object.
Python is for
a cycle in nature is to expand its calling next()
function to achieve, for example:
for x in [1, 2, 3, 4, 5]: pass
In fact fully equivalent to:
# Iterator object is first obtained: IT = ITER ([. 1, 2,. 3,. 4,. 5]) # cycles: the while True: the try: # next value is obtained: X = Next (IT) the except StopIteration: # encountered on StopIteration exit the loop break