Python learning diary: day13 ------ iterator and generator, pythonday13 ------
I. Import 1. the dir function print (dir ([]) tells me that all the methods in this list contain double underscores. 2. The returned value after a list executes _ iter _ () is an iterator 3, the number of _ length_hint _ elements 4, and the value of _ setstate _ from the specified position is 5, []. _ iter _ () iterator ----> _ next _ you can use next to get values from the iterator one by one. 6. _ next _ () in the iterator _() method 2 can be obtained one by one. iterator concept iterator Protocol: The _ next _ and _ iter _ methods are included in iterator 3. iteratable protocols: as long as the _ iter _ method is contained, it can be iterated (all can be for loop) 4. It can be iterated-> the iterator can be iterated +. _ iter _() method to obtain an iterator. 5. for Loop and for loop are used only when the iterator is an object that can be iterated. for, when we encounter a new variable, when you are not sure whether it can be used for a loop, you can determine whether it can be iterated. Vi. Advantages of the iterator: # Take one value from the container type, all values are obtained. # memory space can be saved. # The iterator does not occupy a large block of memory in the memory. Instead, it generates, each time next gives me a 7. Generator 1, the essence of the generator is iterator 2, generator Function
def generator(): print('1') yield 'a'ret =generator ()print(ret)
As long as all the keyword functions containing yield are generator functions, and yield and return cannot be shared, they must be written inside the function.
# As long as it is a generator function: after execution, a generator will be obtained as the return value.
Def generator (): print (1) yield 'A' # generator function: after execution, a generator is obtained as the return value ret = generator () print (ret. _ next _())
Def wahaha (): for I in range (20000): yield 'wahaha % s' % I
3. Input of the listener File
Def tail (filename ):
F = open ('file', encoding = 'utf-8') while True: line = f. readline () if line. strip (): yield line. strip () g = tail ('file') for I in g: if 'python' in I: print (I)