如何从生成器中生成对象并立即将其忘记,以便它不占用内存?
例如,在以下功能中:
def grouper(iterable, chunksize):
"""
Return elements from the iterable in `chunksize`-ed lists. The last returned
element may be smaller (if length of collection is not divisible by `chunksize`).
>>> print list(grouper(xrange(10), 3))
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
"""
i = iter(iterable)
while True:
chunk = list(itertools.islice(i, int(chunksize)))
if not chunk:
break
yield chunk
Run Code Online (Sandbox Code Playgroud)
我不希望函数chunk在产生它之后保持引用,因为它不会被进一步使用并且只消耗内存,即使所有外部引用都消失了.
编辑:使用python.org的标准Python 2.5/2.6/2.7.
解决方案(几乎同时由@phihag和@Owen提出):将结果包装在(小)可变对象中并匿名返回块,只留下小容器:
def chunker(iterable, chunksize):
"""
Return elements from the iterable in `chunksize`-ed lists. …Run Code Online (Sandbox Code Playgroud) 我在这里阅读了关于Swift中Array的copy-on-write实现.
与标准库中的所有可变大小集合一样,数组使用copy-on-write优化.在您修改其中一个副本之前,阵列的多个副本共享相同的存储.当发生这种情况时,被修改的数组将使用其自身的唯一拥有副本替换其存储,然后对其进行修改.有时应用优化可以减少复制量.
我想知道你是否有任何关于哪种结构支持写时复制的信息.
我有一个非常大的结构,我想确保不会被不必要地复制.如何为它创建一个copy-on-write容器?