加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python-list_iterator是否会垃圾收集其消耗的值?

发布时间:2020-12-17 17:37:23 所属栏目:Python 来源:网络整理
导读:假设我有li = iter([1,2,3,4]). 当我执行next(li)时,垃圾收集器会丢弃对不可访问元素的引用. 而关于双端队列,那么di = iter(deque([1,4]))中的元素一旦消耗就可以被收集. 如果不是,Python中的本机数据结构是否实现这种行为. 最佳答案 https://github.com/pyt

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

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

而关于双端队列,那么di = iter(deque([1,4]))中的元素一旦消耗就可以被收集.

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

最佳答案
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,4])

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读