Python masters road [9] python-based iterator and generator, python Generator
Iterator and Generator
1. iterator
An iterator is a way to access collection elements. The iterator object is accessed from the first element of the set until all elements are accessed. The iterator can only move forward without moving back, but there is nothing to do with it, because people seldom go back on the way of iteration. In addition, the major advantage of the iterator is that it is not required to prepare all elements in the entire iteration process in advance. The iterator calculates an element only when it iterates to an element. Before or after this, the element may not exist or be destroyed. This feature makes it especially suitable for Traversing large or infinite sets, such as several G files.
Features:
>>> a = iter([1,2,3,4,5])>>> a<list_iterator object at 0x101402630>>>> a.__next__()1>>> a.__next__()2>>> a.__next__()3>>> a.__next__()4>>> a.__next__()5>>> a.__next__()Traceback (most recent call last): File "<stdin>", line 1, in <module>StopIteration
2. Generator
When a function is called, an iterator is returned. This function is called a generator. If the function contains the yield syntax, this function will become a generator;
def func(): yield 1 yield 2 yield 3 yield 4
In the code above: func is a function called generator. When you execute this function func (), you will get an iterator.
>>> temp = func()>>> temp.__next__()1>>> temp.__next__()2>>> temp.__next__()3>>> temp.__next__()4>>> temp.__next__()Traceback (most recent call last): File "<stdin>", line 1, in <module>StopIteration
3. Instance
A. Use the generator to customize the range
def xrange(n): start = 0 print(start) while True: if start > n : return yield start start += 1obj = xrange(4)n1 = obj.__next__()n2 = obj.__next__()n3 = obj.__next__()n4 = obj.__next__()n5 = obj.__next__()n6 = obj.__next__()print(n1,n2,n3,n4,n5,n6)
B. Use the iterator to access range