python - list_iterator 垃圾会收集其消耗的值吗?
问题描述
假设我有li = iter([1,2,3,4])
.
当我这样做时,垃圾收集器会丢弃对不可访问元素的引用吗next(li)
?
那么,一旦消耗deque
,元素di = iter(deque([1,2,3,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,2,3,4])
for item in l:
print( len(l) )
推荐阅读
- c# - 从 ASP.NET Core 2.1 中的 MySqlConnector 获取查询日志
- angular - 类型“对象”.ts(2339) 上不存在属性“地图”
- hadoop - 在 Tez 和 Map reduce 中运行“count(*)”时的行为差异
- python-3.x - 对字符串的怀疑
- operating-system - 为什么驱动程序要求 USB 设备发送 USB 描述符?
- php - preg_match_all 和我的字符串有什么问题?
- twilio - 测试时可以获取authy发送的短信内容(包括验证码)吗?
- terraform - 使用 Terragrunt 从一个 Terraform 模块创建多个对象
- flutter - 实现 FadeInImage 时永远加载占位符图像
- sql - 如何在 Linq/Sql 中按当前日期排序?