【问题标题】:Does a list_iterator garbage collect its consumed values?list_iterator 垃圾会收集其消耗的值吗?
【发布时间】:2019-07-06 18:24:16
【问题描述】:

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

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

那么deque 呢,di = iter(deque([1,2,3,4])) 中的元素一旦被消耗就可以被收集。

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

【问题讨论】:

  • 列表迭代器本身不包含对列表中各个元素的引用。它本质上是索引的循环。 list 本身 仍然被迭代器引用,至少在它用完之前是这样。因此,在列表本身被回收之前,列表中的每个元素都会至少有一个有效引用

标签: python python-3.x list garbage-collection deque


【解决方案1】:

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) )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-04
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 2011-11-17
    • 2011-04-25
    相关资源
    最近更新 更多