python迭代器
Good day learners! In our previous tutorial, we learned about Python Operator Overloading. In this tutorial we are going to learn about Python Iterator.
美好的一天学习者! 在上一教程中,我们了解了Python操作符重载 。 在本教程中,我们将学习Python Iterator。
Python迭代器 (Python Iterator)
Knowingly or unknowingly, you have used iterator in your Python code. Basically, an iterator is an object which is used to iterate through an iterable element. Didn’t understand the meaning of the last line? Well, don’t worry. We will make you understand about Python Iterator through our tutorial.
在有意无意的情况下,您已经在Python代码中使用了迭代器。 基本上,迭代器是用于迭代可迭代元素的对象。 不明白最后一行的意思吗? 好吧,别担心。 我们将通过本教程使您了解Python Iterator。
Python迭代器和可迭代元素 (Python Iterator and Iterable Elements)
Most of the objects of Python are iterable. In python, all the sequences like Python String, Python List, Python Dictionary etc are iterable. Now, what is iterator? Suppose, A group of 5 boys are standing in a line. Your are pointing at the first boy and ask him about his name. Then, he replied. After that, you ask the next boy and so on. The below picture will illustrate the thing.
Python的大多数对象都是可迭代的。 在python中,所有序列(如Python String , Python List , Python Dictionary等)都是可迭代的。 现在,什么是迭代器? 假设有5个男孩在排队。 您指着第一个男孩,问他这个名字。 然后,他回答。 之后,您询问下一个男孩,依此类推。 下图将说明问题。
In this case, you are the Iterator!!!! Obviously, the group of boys is the iterable element. Hope you understand now.
在这种情况下,您就是Iterator !!!! 显然,男孩组是可迭代的元素。 希望你现在明白了。
Python迭代器协议 (Python Iterator Protocol)
Python Iterator Protocol includes two functions. One is iter()
and the other is next()
. In this section, we will learn to how to traverse an iterable element using Python Iterator Protocol.
Python迭代器协议包含两个函数。 一个是iter()
,另一个是next()
。 在本节中,我们将学习如何使用Python迭代器协议遍历可迭代元素。
In the previous section, we gave the example of group of 5 boys and you. You are the iterator and the boys group is the iterable element. After knowing the name of one boy, you ask the same question to the next boy.
在上一节中,我们给出了一个由5个男孩和您组成的小组的示例。 您是迭代器,而boys组是可迭代的元素。 知道一个男孩的名字后,您向下一个男孩问同样的问题。
After that, you do it again. iter() function is used to create an iterator of an iterable element. And the next() function is used to iterate to the next element.
在那之后,您再做一次。 iter()函数用于创建可迭代元素的迭代器。 next()函数用于迭代到下一个元素。
Python迭代器示例 (Python Iterator Example)
If the iterator go beyond the number of iterable elements then the next() method will raise StopIteration
exception. See the code below for python iterator example.
如果迭代器超出了可迭代元素的数量,则next()方法将引发StopIteration
异常。 有关python迭代器示例,请参见下面的代码。
list_string = ['Boy 1', 'Boy 2', 'Boy 3', 'Boy 4', 'Boy 5']
iterator_you = iter(list_string)
# point the first boy
output = next(iterator_you)
# This will print 'Boy 1'
print(output)
# point the next boy, the second boy
output = next(iterator_you)
# This will print 'Boy 2'
print(output)
# point the next boy, the third boy
output = next(iterator_you)
# This will print 'Boy 3'
print(output)
# point the next boy, the fourth boy
output = next(iterator_you)
# This will print 'Boy 4'
print(output)
# point the next boy, the fifth boy
output = next(iterator_you)
# This will print 'Boy 5'
print(output)
# point the next boy, but there is no boy left
# so raise 'StopIteration' exception
output = next(iterator_you)
# This print will not execute
print(output)
Output
输出量
Boy 1
Boy 2
Boy 3
Boy 4
Boy 5
Traceback (most recent call last):
File "/home/imtiaz/Desktop/py_iterator.py", line 32, in
output = next(iterator_you)
StopIteration
制作Python迭代器 (Making of a Python Iterator)
However, you can make your own specified Python Iterators. To do so, you have to implement a Python class. I assume that you know about Python Class. If you don’t know about this, you can read our tutorial about Python Class.
但是,您可以创建自己的指定Python迭代器。 为此,您必须实现一个Python类。 我假设您了解Python类。 如果您不了解这一点,可以阅读有关Python Class的教程。
As we have said earlier that, Python Iterator Protocol consist of two methods. So we need to implement those method.
如前所述,Python迭代器协议包含两种方法。 因此,我们需要实现那些方法。
For example, you want to generate a list of fibonacci number so that each time call the next function it returns you the next fibonacci number.
例如,您要生成一个斐波那契编号列表,以便每次调用下一个函数时,它都会向您返回下一个斐波那契编号。
To raise the exception, we limit the value of n below 10. If the value of n reach 10, it will raise an exception. The code will be like this.
为了引发异常,我们将n的值限制为小于10。如果n的值达到10,它将引发异常。 代码将像这样。
class fibo:
def __init__(self):
# default constructor
self.prev = 0
self.cur = 1
self.n = 1
def __iter__(self): # define the iter() function
return self
def __next__(self): # define the next() function
if self.n < 10: # Limit to 10
# calculate fibonacci
result = self.prev + self.cur
self.prev = self.cur
self.cur = result
self.n += 1
return result
else:
raise StopIteration # raise exception
# init the iterator
iterator = iter(fibo())
# Try to print infinite time until it gets an exception
while True:
# print the value of next fibonacci up to 10th fibonacci
try:
print(next(iterator))
except StopIteration:
print('First 9 fibonacci numbers have been printed already.')
break # break the loop
So, the output will be
因此,输出将是
1
2
3
5
8
13
21
34
55
First 9 fibonacci numbers have been printed already.
为什么要制作Python迭代器 (Why Making Python Iterator)
After going through the previous section, a question may arise to your mind that why should we make Python Iterator.
经过上一节后,您可能会想到一个问题,为什么我们应该制作Python Iterator。
Well, we have seen already that iterator can traverse an iterable element. Suppose, in our previous example if we make a list of fibonacci numbers and then traverse it via a Python Iterator, it would take huge memory. But if you create a simple Python Iterator class, you can serve your purpose without consuming that much memory.
好了,我们已经看到迭代器可以遍历可迭代元素。 假设在前面的示例中,如果我们列出了斐波那契数字的列表,然后通过Python迭代器遍历它,则将占用大量内存。 但是,如果您创建一个简单的Python Iterator类,则可以在不消耗大量内存的情况下实现您的目的。
So that’s all for Python Iterator. Hope that you are now able to work with Python Iterator. For any further query, you can use the comment box. Learn and practice as much as you can.
这就是Python Iterator的全部内容。 希望您现在可以使用Python Iterator。 对于任何其他查询,您可以使用注释框。 尽可能多地学习和练习。
#HappyCoding
#HappyCoding
Reference: Python Doc
参考: Python文档
python迭代器