Iterator
1. Iterative protocol and can iterator protocol
Iterator: Iterator iterable: iterable
Iterable protocol: as long as the object contains a __iter__ method it is to be iterative
Iterator protocol: There __next__ and __iter__ method iterator
Iterator implements from a value of a
Check whether the iteration
from collections.abcimport Iterable # Iterable detect whether an object can be iterative
print (isinstance (object data type / iterable)) # detect whether the object is the data type or whether the iteration print (dir (Object)) # can view object can use functions print (set (dir (Object)) - set (the dir (object))) # can be used Functionally between two objects set difference
Check whether the iterator
from collections.abc import Iterator # Iterator iterator it is determined whether print (isinstance ([1,2,3], Iterator))
2. iterator
List itself is iterative, but not iterators
Import the Iterable collections.abc from from the Iterator # Import collections.abc NOTE: python3.7 deprecated the collections module for an import module from collections.abc Li = [. 1, 2,. 3] Print (the isinstance (Li, the Iterator)) # False Print (isinstance (li, Iterable)) # True
How to become a list iterator?
from collections.abc import Iterator lst_iterator = [1,2,3].__iter__() # 调用__iter__()方法 print(isinstance(lst_iterator, Iterator)) # True
Iter () and __iter __ () for generating iterator (iterator)
__iter__ iterator protocol
objects all realized __iter__ agreement, are all iterator object. (Next () have to realize, or can not generate data)
Iter () iterator factory function
where there are definitions have __iter __ () function, support or access protocol sequence, which is defined there __getitem __ () function of the object are possible () function generator plant iterator (Iterable) objects through iter
3. iterator value
= lst_iterator [l, 2,3] .__ ITER __ () Print (lst_iterator .__ Next __ ()) Print (lst_iterator .__ Next __ ()) Print (lst_iterator .__ Next __ ()) # beyond the given range StopIteration
4. Summary iterables iterator
a. Python language may be used for loop traversal, are iterables
b. iterables comprise iterator
c nature of iterators: to be able to traverse the unified python data types, do not care about what each value is
d. iterators are inert in operation, the memory space can be saved
The two iterators:
Born: file handle
The day after tomorrow: iterable .__ iter __ ()
File handle is an iterator, range is an iterable
Builder
1. Gerator essentially iterators, generators are to achieve their own
There are two generators: generator function and a generator expression
2. The function generator
a. generator function returns a generator at the time of execution of the
b. When you call a generator function, it is not the first time does not perform, but get generator object
c. value generator only downward, not looking back
generator_func DEF (): Print (123) yield "aaa" Print (456) yield "bbb" # need to obtain the generator g = generator_func () # g is a generator object to perform this step while not actually execute generator_func It is returned by a generator object generator_func Print (G) # <Object generator generator_func AT 0x0000019899601B88> # using the __next __ () method value ret = g .__ next __ () # ret yield is the value returned by the first print (ret) Next __ .__ = G RET1 () Print (RET1) # used for .. in .. value for G in I: Print ( "I:", I) # a return value of a yield per traversal
3. yield keyword
a. yield with a generator function is
b. yield does not terminate function
c. yield without back when it will return None
4. The value of the generator:
a. __next__ There are several yield can be taken several times
. B for normal fetch cycle value for item in generator:
Other types of data cast list (generator) returns a list of all placed inside the generator content
def generator_func(): print(123) yield "aaa" print(456) yield "bbb" g = generator_func() print(list(g)) # ['aaa', 'bbb']
FUNC DEF (): yield 1 yield 2 for i in FUNC (): Print (list (G)) # print here only a [2], because the time for the previous cycle has got a 1, now go list ( g) to the back can only take 2
generator_func DEF (): Print (123) the yield "AAA" Print (456) the yield "BBB" generator_func () Next .__ __ () # can not directly call, a call corresponding to every new generator print (generator_func () next__ .__) # aaa generator_func () .__ the Next __ () # can not be called directly, the equivalent of every call a new builder Print (generator_func () .__ next__) # aaa for i in generator_func (): # for time It can walk, because only called a generator print ( "i:", i )
5. yield from
yield from behind needs with iterables
FUNC DEF (): the yield from [l, 2,3] Print ( '=============') the yield from "ADFD" for I in FUNC (): Print (I) # Results It can be got according to the order of elements iteration object '' ' . 1 2 . 3 ============= a D F D ' ''
6. send keywords
a. send pass is entered into the parameter value, send not return a value when the next and is the same as in the beginning of the implementation of the generator, with the next can only be
b. When the send transmission parameters, the generator must not have a return yield
c. There are several functions there are several next yield, and can not change the first next, the latter can be changed to send, and send text is the sum of the number of yield
FUNC DEF (): Print (123) value. 1 = # Next the yield value is performed to yield 1, when performing the send, to pass from the start value = send incoming execution Print (value) Print (456) the yield "** * "+ value +" *** " G = func () Print (the Next G .__ __ ()) # push func run, print 123, until the yield return a 1, on the suspension of the print (g.send (" aaa ") after) # then send the execution time, the "aaa" pass go, assigned to the value, and then execute down, printed 456, *** aaa ***
FUNC DEF (): Print (. 1) the yield # 2 Next, when it is implemented here, when send88 come, and not to accept variable ,, 88 Print (. 3) value #. 4 = the yield here, and not send pass values come, the value print empty Print (. 5) the yield value G = FUNC () Print (G .__ Next __ ()) # 2 Print (g.send (88)) #. 4 Print (G .__ Next __ ()) # None
7. Generator with decorator
def wrapper (func): # generator Wolff decorator DEF Inner (* args, ** kwargs): G = FUNC (* args, ** kwargs) # G is a generator g .__ next __ () # activates generator G return return Inner @wrapper DEF average_func (): Total = 0 COUNT = 0 Average 0 = the while True: value = the yield Average Total = value + COUNT +. 1 = Average Total = / COUNT G = average_func () Print (g.send (30))
8. The expression list, the list is derived formula
# / Floating point result is # @ two numbers with decimal points not new_l = [I * I I for in [l, 3,5]] Print (new_l) Print ([I // for I in Range 2 (0,7,2)])
9. A generator expression
= A ( "% D Egg" for I in I% Range (10)) # Value from the producer of three methods: # 1. the __next () Print (A .__ Next __ ()) # 2. for for I in A : Print (I) # 3. List strong revolutions print (list (a))
10. derivations Dictionary
The # key and value of a dictionary swap values The CMCase = { "A": 10, "B":} 20 is new_dic The CMCase = {[K]: The CMCase in K for K} Print (new_dic)
11. The set of derivation of formula (go weight)
new_l = {i*i for i in [1,3,5]} print(new_l)
Example 12
a. Python code and compare the list of expressions
l = [{'name':'alex','age':80},{'name':'egon','age':40},{'name':'yuan','age':30},{'name':'nezha','age':18}] new_l = [] for d in l: new_l.append(d["name"]) print(new_l) l = [{'name':'alex','age':80},{'name':'egon','age':40},{'name':'yuan','age':30},{'name':'nezha','age':18}] print([i["name"] for i in l]) print([i["name"] for i in l if i["age"] > 18])
b. generator expression
# 30 can be less than the number divisible by 3 Print ([I for I in Range (30) IF I% 3 == 0]) # of square of the number divisible by 3 up to 30 Print ([I I * for I in Range (30) if i% 3 == 0])
c. builder on Methods for list mix
DEF Demo (): for I in Range (. 4): the yield I G = Demo () g1 = (I for I in G) G2 = (I for I in g1) Print (List (g1)) # to g1 Lane after taken out value, g1 is empty of print (list (g2)) # g2 is empty # result # [0, 1, 2, 3] # []
summary:
The most common is a list comprehensions --- at work, try to list becomes a generator expression
as far as possible derivation streamline operations, enhance the readability of the code, if the derivation is too complex to be converted into common python code
a list of all derivations can be converted to generator expressions, generator expression should be more, less use of the list of expression
in the code, for nested loop is contraindicated, increase dramatically the complexity of the code