首页 > 解决方案 > list_iterator 垃圾会收集其消耗的值吗?

问题描述

假设我有li = iter([1,2,3,4]).

当我这样做时,垃圾收集器会丢弃对不可访问元素的引用吗next(li)

那么,一旦消耗deque,元素di = iter(deque([1,2,3,4]))是否可以收集。

如果没有,Python 中的本机数据结构是否实现了这种行为。

标签: pythonpython-3.xlistgarbage-collectiondeque

解决方案


https://github.com/python/cpython/blob/bb86bf4c4eaa30b1f5192dab9f389ce0bb61114d/Objects/iterobject.c

对列表的引用一直保持到您迭代到序列的末尾。您可以在 iternext 函数中看到这一点。

双端队列在这里并且没有特殊的迭代器。

https://github.com/python/cpython/blob/master/Modules/_collectionsmodule.c

你可以创建自己的类并定义 __iter__ 和 __next__ 来做你想做的事。像这样的东西

class CList(list):
    def __init__(self, lst):
        self.lst = lst

    def __iter__(self):
        return self

    def __next__(self):
        if len(self.lst) == 0:
            raise StopIteration
        item = self.lst[0]
        del self.lst[0]
        return item

    def __len__(self):
      return len(self.lst)


l = CList([1,2,3,4])

for item in l:
  print( len(l) )

推荐阅读