An iterator must be an iterative object, but an iterative object is not necessarily an iterator.
List,truple,str These are iterative objects, but they are not necessarily iterators. The iterator itself does not know how many times it is going to execute, so it can be understood that it is not known how many elements, each call to next (), will go down one step, is inert.
Iterators provide a way of not relying on index values, so that you can traverse an iterative object that has no index, such as a dictionary, a collection, a file, and so on, and then load that element into memory and then release it, which in contrast saves memory, but we have no way of getting the length of the iterator, and we can only take the value back in turn
How do I create an iterator?
As long as the object itself has a __iter__ method, it can be iterated.
D={' A ': 1, ' B ': 2, ' C ': 3}
D.__ITER__ ()
The __iter__ method under the execution object gets 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 ' > #执行结果
A #第一次print (next (a)) results
b #第二次print (Next (a)) results
.....
Stopiteration #直到取完所有的值会提示这个错误,
What if you don't want this error to occur?
D={' A ': 1, ' B ': 2, ' C ': 3}
I=iter (d)
While True:
Try: #错误会出现的代码
Print (Next (i))
Except stopiteration: #如果从这一句里面捕捉到StopIteration This error prompt if execution break occurs
Break
There's a simpler way.
D={' A ': 1, ' B ': 2, ' C ': 3}
d.__iter__
#这里的d默认帮我们执行了d. __iter__ (), and the program automatically helps us catch stopiteration This error, we do not need to write it in hand
Print (k)
How can I tell if an object is an iterative object or an iterator?
Here we need a module to help us
Judging whether it is possible to iterate, with iterable
From collections import Iterable,iterator #我们需要用到的模块
s= ' Hello '
l=[1,2,3]
T= (a)
D={' a ': 1}
set1={1,2,3,4}
F=open (' A.txt ')
# #都是可迭代的
s.__iter__ () #都有__iter__方法
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))
Judging is not an iterator, with 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))
Python iterators and iterative objects