Python3 iterators and generators
Iterator
Iteration is one of the most powerful features of Python is a way to access the collection elements. .
An iterator is a traversal of the object can remember the location.
Iterator object is accessible from the beginning of the first element of the collection until all elements are accessed completely ended. Iterator can only move forward not backward.
Iterator has two basic methods: iter () and next ().
String, list, or tuple objects can be used to create an iterator:
>>> list=[1,2,3,4] >>> it = iter(list) # 创建迭代器对象 >>> print (next(it)) # 输出迭代器的下一个元素 1 >>> print (next(it)) 2 >>>
Iterator object can be used for conventional traverse statement:
#!/usr/bin/python3 list=[1,2,3,4] it = iter(list) # 创建迭代器对象 for x in it: print (x, end=" ")
The above program, the output results are 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()
The above program, the output results are as follows:
1 2 3 4
Builder
In Python, using the yield function is known as a generator (generator).
The difference is that with an ordinary function, the generator is a return iterator function can only be used iterative operations, more simple to understand Builder is an iterator.
Calling the generator is running the process, encountered yield function will pause each time and save all of the current operating information, the return value of yield. Continue running from the current location and the next execution next () method.
The following example uses the yield realized Fibonacci columns:
#!/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()
The above program, the output results are as follows:
0 1 1 2 3 5 8 13 21 34 55