【问题标题】:How does iter() convert the list into the iterator object?iter() 如何将列表转换为迭代器对象?
【发布时间】:2021-09-04 08:24:43
【问题描述】:

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

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

【问题讨论】:

  • 它不会将列表转换为迭代器对象,它会创建一个与列表关联的对象。将其视为具有自己属性的某个内部 Python 类的实例(例如列表的下一个索引应该是什么)。

标签: python iterator iteration iterable


【解决方案1】:

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

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:迭代器是对象,和每个对象一样,它也有字段。而迭代器使用这些字段来存储关于迭代的信息

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2022-01-08
      • 2012-03-02
      • 2012-04-24
      • 2020-04-11
      • 1970-01-01
      • 2018-10-29
      • 2016-08-12
      • 1970-01-01
      相关资源
      最近更新 更多