Python development [Article 1] Generator and iterator of Python basics, Article 1 python
Generator and iterator
1. 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 3ret = func()for i in ret: print(i)
Go to the function to find yield and return the data after yield.
def myrange(arg): start = 0 while True: if start > arg: return yield start start += 1ret = myrange(3)r = ret.__next__()print(r)r = ret.__next__()print(r)r = ret.__next__()print(r)r = ret.__next__()print(r)
2. iterator
Code rendering (Compilation) is executed from bottom up, and code execution is performed from top down.
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:
Inside the iterator is _ next __, and inside the for loop is encapsulated as _ next __.
Illustration:
3. Instance
A. Use the generator to customize the range
def nrange(num): temp = -1 while True: temp = temp + 1 if temp >= num: return else: yield temp
B. Use the iterator to access range
...