Py3start
Iterators
Iterators are a way to access the elements of a collection. The iterator object is accessed from the first element of the collection until all of the elements have been accessed and finished. Iterators can only move forward without going backwards, but that's fine, because people seldom retreat in the middle of an iteration. In addition, one of the great advantages of iterators is that they do not require that all elements in the entire iteration be prepared in advance. An iterator computes an element only when it iterates over it, and before or after that, the element may not exist or be destroyed. This feature makes it ideal for traversing large or infinite collections, such as several G files
Characteristics:
- The visitor does not need to care about the structure inside the iterator, but simply continues to fetch the next content through the next () method
- A value in the collection cannot be accessed randomly, and can only be accessed from beginning to end
- You can't go back halfway through the interview.
- Facilitates recycling of large data sets, saving memory
Example:
#!/usr/bin/python
#coding=utf-8
names=iter([‘yaobin‘,‘hy‘,‘test‘])
print(names)
print(names.__next__())
print(names.__next__())
print(names.__next__())
print(names.__next__())
结果:
<list_iterator object at 0x00000000010ED160>
yaobin
hy
test
Traceback (most recent call last):
File "D:/Users/bin/PycharmProjects/s12/day4/迭代器", line 11, in <module>
print(names.__next__())
StopIteration
#迭代器只有__next__方法, there's nothing else.
End
From for notes (Wiz)
Day④: iterators