python iterator summary

First, the difference between iterable objects and iterators

Iterable object (Iterable) : It is an object that implements the __iter__() method. When __iter__() is called, an iterator object can be returned. Everything that can be iterated over by a for loop is an iterable object

You can use isinstance() to determine whether it is an iterable object. Common iterable objects are as follows: list, tuple, string, dictionary, file, socket

from collections import Iterable 
print(isinstance([], Iterable)) #True
print(isinstance('abc',Iterable)) #True
print(isinstance(iter([]),Iterable)) #True
print(isinstance(233,Iterable)) #True

 

 


Iterator ( Iterator ) : Not only implements the __iter__() method, but also the __next__() method. The next element can be continuously produced by the next() method until StopIteration throws an error.

from collections import Iterator
print(isinstance([], Iterator)) #False
print(isinstance('abc',Iterator)) #False
print(isinstance(iter([]),Iterator)) #True
print(isinstance((i for i in range(5)),Iterator)) #True

 


Some limitations of iterators:

# 1. The iterator can only continuously take the next element and cannot return 
# 2. The iterator cannot be copied directly and simply 
# 3. The iterator will report an error if it exceeds the range

 


 

Second, the generation of iterators

ls=[1,2,3]
print(type(ls)) #<class 'list'>
ls_i=iter(ls)
print(type(ls_i)) #<class 'list_iterator'>

 


We can use dir to see what methods the iterator has:

print(dir(ls_i))
#['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', 
'__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__length_hint__', '__lt__', '__ne__', '__new__', 
'__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', 
'__subclasshook__']

 

The above __iter__ and __next__ are generated to implement the iterator protocol.
Below we introduce the iter() and next() methods inside the iterator: iter() returns the iterator itself. next() returns the next element of the iterator.

ls = [1,2,3 ]
ls_i=iter(ls) #生成迭代器
a=ls_i.__iter__() 
print(a) 
print(ls_i)
print(a.__next__())
print(a.__next__())
print(ls_i.__next__())

 


The result of running the above code is as follows:

<list_iterator object at 0x005C16F0>
<list_iterator object at 0x005C16F0>
1
2
3

 


3. Writing an iterator by yourself is
mainly to write and implement the iter() and next() methods:

class listIterator(object):
    def __init__(self,data):
        self.__data=data
        self.__count=0     
    def __iter__(self):
        return self
    def __next__(self):
        if self.__count<len(self.__data):
            val=self.__data[self.__count]
            self.__count+=1
            return val
        else:
            raise StopIteration
ls=listIterator([1,2,3])
for i in ls:
    print(i)

 

 The above code implements a simple iterator. Which defines a count variable, the function of this variable is to record which element the iterator goes to. We need to know that the iterator is one-time, after we generate an element, the iterator will

Delete this element, so we need to keep track of which element we went to. See the code above for details. Let's further deepen the understanding of count through an example.

ls=[1,2,3,4,5]
for i in ls:
    print(i)
    ls.remove(i)
print (ls)

 

The above output is like:

1
3
5
[2, 4]

 

Why is this so. In fact, the essence of the for loop is to first call the __iter()__ method of ls to turn the list into an iterator, and then use next() to generate each element. Remember count is the number of elements the record iterator goes to! !

Let's take a closer look at the operation of the entire function.

count=0 generates 1 remove 1 then ls=[2,3,4,5 ]
count = 1 At this time, 3 is generated, because count is the first element of the record list. Regardless of whether the original list has changed. So after remove ls=[2,4,5 ]
count =2, output the third element 5, then remove, and finally ls=[2,4 ]
count = 3, greater than the length of the list, directly end for

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325246961&siteId=291194637