Generator generator and iterators Iterator

First, the list of Formula
       Before learning a generator iterator first look at what is a list of the formula, the formula is a list of Python's built a very simple but powerful can be used to create a list of the formula. What does this mean? For example, if you want to generate a list of [0,1,2,3,4,5] may be used list (range (6)), but if you want to generate [,,,,,] i.e. [0,1,4 , 9,16,25] how to do?

Method # a: circular
>>> L = []
>>> for X in Range (. 6):
... L.append (X ** 2)
...
>>> L
[0,. 1,. 4,. 9 , 16, 25]
# method II: list formula
>>> [X ** 2 for X in Range (. 6)]
[0,. 1,. 4,. 9, 16, 25]
        observation method, two methods can be found, use the list of formula method two more concise, clear, method two is to generate a list of style. A few examples come to a better understanding:

# Square calculation between the even positive integer 0-5
>>> [X ** 2 for X in Range (. 6) IF X% 2 == 0]
[0,. 4, 16]

# listing using two variables formula
> D = {>> 'A': '. 1', 'B': '2', 'C': '. 3'}
>>> [K + '=' for K + V, V in d.items ()]
[ 'a = 1', ' b = 2', 'c = 3']
II generator
       by formula list, a list can be created directly. However, subject to memory limitations, the list is certainly limited capacity. Also, create a list containing one million elements, not only take up much storage space, if we only need to access the first few elements behind the elements that the vast majority of occupied space are wasted.

       So, if the list element can be calculated out in accordance with an algorithm that whether it can continue to calculate subsequent elements in the cycle? This eliminates the need to create a complete list, thus saving a lot of space. In Python, while circulating mechanism for this calculation, known as a generator: generator.

 1. How to create generator

        Method One: Create a generator easiest way is to generate a list of type [] read (), creates a generator: 

# List formula 
>>> L = [X ** 2 for X in Range (. 6 )]
 >>> L 
[0, . 1,. 4,. 9, 16, 25 ] 
 
# generator 
>>> g = (x * 2 * for X in Range (. 6 ))
 >>> g
 <Object Generator <genexpr> AT 0x00000173FFBFA1A8> 
 
NOTE: the difference is that only the L and g is the outermost layer [] and (), L is a list, and g is a generator.

     Method two: function becomes normal make generator (generator), only the print (b) will be able to yield b. If a function is included in the yield keyword, then this function is no longer an ordinary function, but a generator (generator).

 2. How do you get each element generator?

       Method a: To a a next print can be obtained the function generator by next () returns a value. Save generator is the algorithm, each call to next (), then calculate the value of an element g until calculate to the last element, there are no more elements thrown StopIteration error.

#通过next()获得生成器的每一个元素
>>> g = (x**2 for x in range(6))
>>> g
<generator object <genexpr> at 0x00000173FFBFA1A8>
>>> next(g)
0
>>> next(g)
1
>>> next(g)
4
>>> next(g)
9
>>> next(g)
16
>>> next(g)
25
>>> next(g)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

  Method two: using a for loop

# Is obtained by the generator for each cycle a value 
>>> G = (X ** 2 for X in Range (. 6 ))
 >>> for I in G: 
...      Print (I) 
... 
0
 . 1 
. 4 
9 
16 
25

Example 3. Generator

       Exercise a: well-known Fibonacci number (the Fibonacci), except for the first and second number, any number may be obtained by adding by the first two numbers: 1,1,2,3,5,8 , 13,21,34 ... with a list of formula write to, how to use the function?

#方法一:
>>> def fib(max):
...     n,a,b = 0,0,1
...     while n < max:
...             print(b)
...             a,b = b,a+b
...             n += 1
...     return 'done'
...
>>> fib(6)
1
1
2
3
5
8
'done'
 
#注:a,b = b,a+b  相当于 t = (b,a+b)  a = t[0]  b = t[1]
#方法二:生成器
>>> def fib(max):
...     n,a,b = 0,0,1
...     while n < max:
...             yield b
...             a,b = b,a+b
...             n += 1
...     return 'done'
...
>>> f = fib(6)
>>> f
<generator object fib at 0x00000173FFBFA1A8>
>>> for i in f:
...     print(i)
...
1
1
2
3
5
8

  The most difficult to understand is the execution flow generator and the function is not the same. Function is the execution order, encountered a return statement or statement returns the last line of the function. Becomes a function generator, each time next call () is executed, encounters yield return statement, the statement of the yield from the last execution again returned to continue.

# Perform generator function each time the next call () when he met yield return statement, the statement from the yield at last returned again to continue the implementation
  
>>> DEF the ODD (): 
...      Print ( ' first step ' ) 
...      the yield 100 
...      Print ( ' second step ' ) 
...      the yield 200 is 
...      Print ( ' the third step ' ) 
...      the yield 300 
...
 >>> G = ODD ()
 >>> Next (G) 
Step
 100 
>>> Next (G) 
Step
 200 
>>>next (g) 
a third step
 300 
>>> next (g) 
Traceback (MOST Recent Last Call): 
  File " <stdin> " , Line. 1, in <Module1> 
the StopIteration
 >>> # ODD () function generator, in encountered in implementation yield is interrupted, the next to continue. After performing three times yield, has no yield can be executed, so the 4th call error.
 

Builder Summary:

       a, in Python may simply list generator to formula, can also be achieved through complex logic function generator. Generator works in the cycle for the next element is calculated continuously, and the end for the appropriate conditions. For functions into the generator, the return statement is encountered or the last line of the statement to execute the function body, that is the end of the generator's instruction, for the cycle ends.

       B difference, and a normal function generator function: ordinary function call returns the result directly, the generator function "call" actually returns a generator object

# Ordinary function 
>>> R & lt ABS = (-1 )
 >>> R & lt
 . 1 # generator function 
>>> FIB G = (. 6 )
 >>> G
 <Object Generator FIB AT 0x00000173FFBFA1A8>
 

Third, the iterator
       can act directly on the data type of the for loop are the following:

       A class is a collection of data types, such as a list, tuple, dict, set, str like;

       One is the generator, comprising a generator and a band of yield generator function.

       These can act directly on an object referred to as a for loop iterables: Iterable. Can use the isinstance () determines whether an object is an object Iterable:

#判断一个对象是否是可迭代对象Iterable
>>> from collections import Iterable
>>> isinstance([],Iterable)
True
>>> isinstance((),Iterable)
True
>>> isinstance({},Iterable)
True
>>> isinstance('aaa',Iterable)
True
>>> isinstance((x for x in range(5)),Iterable)
True
>>> isinstance(100,Iterable)
False
>>> isinstance(True,Iterable)
False

May be next () function call and return to the next target value continuously referred iterator: Iterator. Can use the isinstance () determines whether an object is an object Iterator:

#判断一个对象是否是迭代器:Iterator
>>> from collections import Iterator
>>> isinstance([],Iterator)
False
>>> isinstance((),Iterator)
False
>>> isinstance({},Iterator)
False
>>> isinstance('aaa',Iterator)
False
>>> isinstance((x for x in range(5)),Iterator)
True

Can be found in the generator are iterator (Iterator) objects, but list, tuple, dict, str although iterables (Iterable), not the iterator (Iterator). That there is no way to make the list, tuple, dict, str and other iterables (Iterable) becomes iterator (Iterator)? Iter () function that can do this!

# ITER () will list, tuple, dict, set, str becomes like iterables iterator 
>>> the isinstance (ITER ([]), the Iterator) 
True
 >>> the isinstance (ITER (()), the Iterator) 
True
 >>> the isinstance (ITER ({}), the Iterator) 
True
 >>> the isinstance (ITER ( ' AAA ' ), the Iterator) 
True

Why list, dict, str and other data types are not Iterator? This is because Python's iterator (Iterator) object represents a data stream, the iterator (Iterator) objects can be next () function call to return and continue to 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 to function under the on-demand computing to achieve a data next (), so the calculation Iterator is inert, only need to return it will calculate when the next data.

       Iterator (the Iterator) may even represent an infinite stream, e.g. all natural numbers. The list is never stored using all natural numbers.

Iterator Summary:

       a, can be applied to all objects are available for loop iteration (the Iterable) type;

       B, usually a sequence of calculations may be applied to the inert next () function are iterator objects (the Iterator) type, they represent;

       c, a set of data types, such as list, dict, str, etc. may all iteration (the Iterable) but not iterator (Iterator), but may () function to get an iterator (the Iterator) objects through iter.

       d, a for loop nature of Python is by constantly calling next () function to achieve.

for X in [. 1, 2,. 3,. 4,. 5 ]:
     Pass 
 
practically completely equivalent to: 
 
# first obtaining Iterator objects: 
IT = ITER ([. 1, 2,. 3,. 4,. 5 ])
 # cycles: 
the while True :
     the try :
         # get the next value: 
        the X-= the next (IT)
     the except StopIteration:
         # encounter StopIteration loop exits 
        break

Fourth, the iterator relationship builder


       1. For iterables, () function is obtained through the ITER iterator object, and may be next () function call returns the next data and continue until there is no data error is thrown StopIteration.

       2. The generator is a special iterator generated by the generator function generator, the generator function may be defined by a conventional def statement, but no return to return, but returns a result of yield with time. return yield differs in that the return after the return, the release function, but does not generate. In direct call next () method or be used for the next iteration statement, the generator will be started from a lower yield, until the next encounter a yield.

       3. iterator can be several iterations, and can only generate one iteration.

# Iterator: multiple iterations may 
>>> G = [X * X for X in Range (. 5 )]
 >>> G 
[0, . 1,. 4,. 9, 16 ]
 >>> for I in G: 
.. .      Print (I) 
... 
0
 . 1 
. 4 
. 9 
16 
>>> G 
[0, . 1,. 4,. 9, 16 ]
 >>> for I in G: 
...      Print (I) 
... 
0
 . 1 
. 4 
. 9 
16 # Builder: only one iteration 
>>> f = (x * x
 
 
for x in range(5))
>>> f
<generator object <genexpr> at 0x0000022BA065F0F8>
>>> for i in f:
...     print(i)
...
0
1
4
9
16
>>> f
<generator object <genexpr> at 0x0000022BA065F0F8>
>>> for i in f:
...     print(i)
...
>>>

 

Guess you like

Origin www.cnblogs.com/ceo-python/p/11599631.html