Python3中迭代器介绍
Posted fengbingchun
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python3中迭代器介绍相关的知识,希望对你有一定的参考价值。
Python中一个可迭代对象(iterable object)是一个实现了__iter__方法的对象,它应该返回一个迭代器对象(iterator object)。迭代器是一个实现__next__方法的对象,它应该返回它的可迭代对象的下一个元素,并在没有可用元素时触发StopIteration异常。
当我们使用for循环遍历任何可迭代对象时,它在内部使用iter()方法获取迭代器对象,该迭代器对象进一步使用next()方法进行迭代。此方法触发StopIteration以表示迭代结束。
Python中大多数内置容器,如列表、元组、字符串等都是可迭代的。它们是iterable但不是iterator,把它们从iterable变成iterator可以使用iter()函数。
测试代码如下:
# reference: https://www.programiz.com/python-programming/iterator
my_list = [1, 3, 5] # define a list
if 0:
my_iter = iter(my_list) # get an iterator using iter()
print(next(my_iter)) # iterate through it using next()
print(my_iter.__next__()) # next(obj) is name as obj.__next__()
print(my_iter.__next__()) # 5
#print(my_iter.__next__()) # this will raise error(StopIteration), no items left
else: # use the for loop
for element in iter(my_list): # 迭代器对象可以使用for语句进行遍历
print(element, end=" ")
'''
for element in iterable:
# do something with element
Is actually implemented as:
# create an iterator object from that iterable
iter_obj = iter(iterable)
while True: # infinite loop
try:
# get the next item
element = next(iter_obj)
# do something with element
except StopIteration:
# if StopIteration is raised, break from loop
break
'''
# reference: https://www.geeksforgeeks.org/iterators-in-python/
class Test:
def __init__(self, limit):
self.limit = limit
# Creates iterator object, Called when iteration is initialized
def __iter__(self):
self.x = 10
return self
# To move to next element. In Python 3, we should replace next with __next__
def __next__(self):
# Store current value ofx
x = self.x
# Stop iteration if limit is reached
if x > self.limit:
raise StopIteration
# Else increment and return old value
self.x = x + 1
return x
# Prints numbers from 10 to 15
print("\\n")
for i in Test(15):
print(i, end=" ")
print("\\n")
value = iter(Test(11))
print(next(value))
print(next(value))
#print(next(value)) # raise StopIteration
print("test finish")
以上是关于Python3中迭代器介绍的主要内容,如果未能解决你的问题,请参考以下文章