python iterators and iterables

An iterator must be an iterable object, but an iterable object is not necessarily an iterator.

 list, truple, str are all iterable objects, but they are not necessarily iterators. The iterator itself does not know how many times it needs to be executed, so it can be understood that it does not know how many elements there are. Every time next() is called, it will go down one step, which is lazy.

Iterators provide a way to retrieve values ​​without relying on indexes, so that iterable objects without indexes, such as dictionaries, sets, files, etc., can be traversed, and this element is loaded into memory and then released, which saves memory by comparison. , but we have no way to get the length of the iterator, and we can only take values ​​in sequence.


How to create an iterator?

As long as the object itself has an __iter__ method, it is iterable.

d={'a':1,'b':2,'c':3}
d.__iter__()

Execute the __iter__ method under the object to get the iterator

d={'a':1,'b':2,'c':3}
a=d.__iter__()
print(type(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))
<class 'dict_keyiterator'> #Execution result 
a #First print(next(a)) result
b #Second print(next(a)) result
.....

StopIteration #It will prompt until all values ​​are taken this error,

What if I don't want this error to appear?

d={'a':1,'b':2,'c':3} 
i=iter(d)
while True:
try: #the code where the error will occur
print(next(i))
except StopIteration: #if Catch the StopIteration error message from this sentence, if there is a break
break

 There is an easier way

d={'a':1,'b':2,'c':3} 
d.__iter__

for k in d: #Here d executes d.__iter__() for us by default, and the program automatically captures it for us StopIteration This error does not require us to manually write it into
print(k)

How to judge whether an object is an iterable object or an iterator?

Here we need a module to help us

To determine whether it is iterable, use Iterable

from collections import Iterable,Iterator #The modules we need to use 

s='hello'
l=[1,2,3]
t=(1,2,3)
d={'a':1}
set1={1, 2,3,4}
f=open('a.txt')

# #All are iterable
s.__iter__() #All have __iter__ methods
l.__iter__()
t.__iter__()
d.__iter__()
set1.__iter__()
f.__iter__()
print(isinstance(s,Iterable))
print(isinstance(l,Iterable))
print(isinstance(t,Iterable))
print(isinstance(d,Iterable))
print(isinstance( set1,Iterable))
print(isinstance(f,Iterable))

To determine whether it is an iterator, use Iterator

print(isinstance(s,Iterator))
print(isinstance(l,Iterator))
print(isinstance(t,Iterator))
print(isinstance(d,Iterator))
print(isinstance(set1,Iterator))
print(isinstance(f,Iterator))

 

Guess you like

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