Python迭代器
在本教程中,我们将学习Python Iterator。
Python迭代器
在有意或者无意的情况下,您已在Python代码中使用了迭代器。
基本上,迭代器是用于迭代可迭代元素的对象。
不明白最后一行的意思吗?好吧,别担心。
我们将通过本教程使您了解Python Iterator。
Python迭代器和可迭代元素
Python的大多数对象都是可迭代的。
在python中,所有序列(例如Python字符串,Python列表,Python词典等)都是可迭代的。
现在,什么是迭代器?假设有一个由5个男孩组成的小组排成一行。
您指着第一个男孩,问他这个名字。
然后,他回答。
之后,您询问下一个男孩,依此类推。
下图将说明问题。
在这种情况下,您就是Iterator !!!!显然,男孩组是可迭代的元素。
希望你现在明白了。
Python迭代器协议
Python迭代器协议包含两个函数。
一个是iter()
,另一个是next()
。
在本节中,我们将学习如何使用Python迭代器协议遍历可迭代元素。
在上一节中,我们给出了一个由5个男孩和您组成的小组的示例。
您是迭代器,而boys组是可迭代的元素。
知道一个男孩的名字后,您向下一个男孩问同样的问题。
在那之后,您再做一次。
iter()函数用于创建可迭代元素的迭代器。
next()函数用于迭代到下一个元素。
Python迭代器示例
如果迭代器超出了可迭代元素的数量,则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)
输出
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迭代器
但是,您可以创建自己的指定Python迭代器。
为此,您必须实现一个Python类。
我假设您了解Python类。
如果您不了解此信息,可以阅读有关Python类的教程。
如前所述,Python迭代器协议包含两种方法。
因此,我们需要实现那些方法。
例如,您要生成一个斐波那契数字的列表,以便每次调用下一个函数时,它都会向您返回下一个斐波那契数字。
为了引发异常,我们将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
因此,输出将是
1 2 3 5 8 13 21 34 55 First 9 fibonacci numbers have been printed already.
为什么要制作Python迭代器
在阅读了上一节之后,您可能会想到一个问题,我们为什么要制作Python Iterator。
好了,我们已经看到迭代器可以遍历可迭代的元素。
假设在前面的示例中,如果我们列出了斐波那契数字的列表,然后通过Python迭代器遍历它,则将占用大量内存。
但是,如果您创建一个简单的Python Iterator类,则可以在不消耗大量内存的情况下实现您的目的。