Python3 iterators and generators
Iteration is one of the most powerful features of Python and is a way to access collection elements. .
An iterator is an object that can remember the position of the traversal.
The iterator object starts accessing from the first element of the collection until all elements have been accessed. Iterators can only go forward and not backward.
Iterators have two basic methods: iter() and next().
String, list or tuple objects can be used to create iterators:
>>> list=[1,2,3,4] >>> it = iter(list) # 创建迭代器对象 >>> print (next(it)) # 输出迭代器的下一个元素 1 >>> print (next(it)) 2 >>>
Iterator objects can be traversed using regular for statements:
#!/usr/bin/python3 list=[1,2,3,4] it = iter(list) # 创建迭代器对象 for x in it: print (x, end=" ")
Execute the above program, The output result is as follows:
1 2 3 4
You can also use the next() function:
#!/usr/bin/python3 import sys # 引入 sys 模块 list=[1,2,3,4] it = iter(list) # 创建迭代器对象 while True: try: print (next(it)) except StopIteration: sys.exit()
Execute the above program, the output result is as follows:
1 2 3 4
Generator
In Python, a function that uses yield is called a generator.
Different from ordinary functions, a generator is a function that returns an iterator and can only be used for iterative operations. It is easier to understand that a generator is an iterator.
During the process of calling the generator, each time it encounters yield, the function will pause and save all current running information and return the value of yield. And continue running from the current position the next time the next() method is executed.
The following example uses yield to implement the Fibonacci sequence:
#!/usr/bin/python3 import sys def fibonacci(n): # 生成器函数 - 斐波那契 a, b, counter = 0, 1, 0 while True: if (counter > n): return yield a a, b = b, a + b counter += 1 f = fibonacci(10) # f 是一个迭代器,由生成器返回生成 while True: try: print (next(f), end=" ") except StopIteration: sys.exit()
Execute the above program and the output result is as follows:
0 1 1 2 3 5 8 13 21 34 55