本文介绍了list_iterator是否会垃圾收集其消耗的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

当我执行next(li)时,垃圾收集器会删除对不可访问元素的引用.

Will the garbage collector drop the references to inaccessible element when I do next(li).

deque一样,di = iter(deque([1,2,3,4]))中的元素一旦被消耗,将可被收集.

And what about deque, will elements in di = iter(deque([1,2,3,4])) be collectable once consumed.

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

If not, does a native data structure in Python implement such behaviour.

推荐答案

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

将保留对列表的引用,直到您迭代序列的末尾为止.您可以在iternext函数中看到这一点.

A reference to the list is held until you iterate to the end of the sequence. You can see this in the iternext function.

双端队列在这里,没有特殊的迭代器.

The deque is here and has no special iterator.

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

您可以创建自己的类,并定义__iter__和__next__以执行所需的操作.像这样

You can create your own class and define __iter__ and __next__ to do what you want. Something like this

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

这篇关于list_iterator是否会垃圾收集其消耗的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 06:49