First, the Import 1,dir function print (dir ([])) tells me that this list has all the methods with double underlines are called double-down methods. 2, a list is executed after _iter_ () The return value is an iterator 3,_length_hint_ the number of elements 4,_setstate_ from the specified position 5,[]._iter_ () iterator---->_next_ By next you can take a value from an iterator of 6, the _next_ () method in the iterator can be one to get the value of the second, the iterator conceptiterator protocol: An iterator that internally contains the _next_ and _iter_ methodsThird, the possible iterativeiterative protocol: As long as the containing _iter_ method is iterative (can be used for loop)Iv. iterative iterative +._iter_ () method can be used to get an iterator.v. for loops and iteratorsThe For loop is the use of iteratorsIt is only possible to iterate over objects to use the forwhen we come across a new variable and don't know if we can do it for the loop, we can tell if it's iterative. Six, the benefits of iterators:#从容器类型中一个一个的取值, will take all the values to the # can save the memory space #迭代器并不会在内存中再占用一个大块内存, but with each time the loop generates one, each time next gives me a seven, generator 1, the essence of the generator is the iterator 2, the generator function
def generator (): Print ('1') yield ' a ' =Generator ()print(ret)
As long as the keyword function with yield is a generator function and yield is not shared with return and needs to be written inside the function
#只要是生成器函数: After execution, a generator is given as the return value.
def generator (): Print (1) yield ' a ' # generator function: After execution, you get a generator as the return value ret = generator ()print(ret)print( Ret._next_ ())
def Wahaha (): for in range (20000): yield ' wahaha%s'%i
3. Input of the listening file
def tail (filename):
F =open (' file ', encoding = ' utf-8 ') while true:line = F.readline () if Line.strip (): Yield Line.strip () g = Tai L (' file ') for I in G:if ' Python ' in I:print (i)
Python Learning Diary: DAY13------iterators and generators