iter() 如何将列表转换为迭代器对象?

问题描述

我知道 iter() 函数list(或其他集合)转换为迭代器对象。但我不能完全理解迭代器对象是什么。

我读到它是无序数据,其中的每个元素(在调用 __next__() 之后)都分配给了局部变量。但是计算机如何知道迭代器的下一个元素将是什么?

解决方法

迭代器对象将这些信息存储在其字段中。像这样(我们假设我们的数组使用正常索引):

class IteratorObject:
    def __init__(self,iterated_array) :
        self.iterated = iterated_array 
        self.current_index = 0 # starting index is 0

    def __iter__(self) :
        return self # there isnt reason to create new iterator object - we will return existing one

    def __next__(self) :
        #if current_index is bigger that length of our array,we will stop iteration
        if self.current_index >= len(self.iterated):
            raise StopIteration() #this is exception used for stopping iteration
   
        old_index = self.current_index
        self.current_index += 1

        return self.iterated[old_index

您可以看到迭代器对象具有存储当前索引(current_index)的内部字段。如果这个索引大于迭代数组的长度,我们将结束迭代(使用 StopIteration 异常)。

您可以以任何您想要的方式实现迭代器。就像您可以拥有从数组末尾迭代到数组开头的迭代器一样 - 您只需要从最后一个索引开始并以 0 索引结束。

Tl;dr:迭代器是对象,就像每个对象一样,它有字段。并且迭代器使用这些字段来存储有关迭代的信息

,

可以在 iter() 中使用迭代器(具有 __iter__ 方法的对象)。 迭代有两种方式。

  1. iter 返回一个迭代器。当 iter() 被调用时,它返回一个已经 iterd 的列表(当你 iter() 一个列表时)这将一直持续,直到迭代的对象是一个内置对象,实际上可以使它成为自己的迭代器。