简体   繁体   English

Python语句使用过多的RAM

[英]Python statement uses excessive amounts of RAM

This simple statement: 这个简单的陈述:

zip(xrange(0, 11614321), xrange(0, 11627964))

...is eating most of my RAM. ......吃掉了我的大部分内存。 (>150 MiB!) Why? (> 150 MiB!)为什么?

Edit: Ah, re-reading the docs, I see zip returns a list, not an iterable. 编辑:啊,重新阅读文档,我看到zip返回一个列表,而不是一个可迭代的。 Anything like zip that returns an iterable? zip那样返回一个可迭代的东西?


The larger picture: I'm iterating over two large arrays of file data, and I'm doing things like iterating (0-end, 0-end), (0-end, 1-end), etc. I'd like to not slice the array, as it would cause excessive allocations of memory. 更大的图片:我正在迭代两个大的文件数据数组,我正在做迭代(0-end,0-end),(0-end,1-end)等等。我喜欢不切片数组,因为它会导致过多的内存分配。 I figured I'd just iterate over the indexes instead, but that doesn't seem to work, as per above. 我想我只是迭代索引,但这似乎不起作用,如上所述。 The whole code: 整个代码:

def subsequence_length(data_a, data_b, loc_a, loc_b):
    length = 0
    for i_a, i_b in zip(xrange(loc_a, len(data_a)), xrange(loc_b, len(data_b))):
        if data_a[i_a] == data_b[i_b]:
            length += 1
        else:
            break
    return length

使用itertools中的izip

If for some reason you didn't want to use the itertools module, it would be trivial to write your own iterator that did the same thing, at least if you know you're dealing with exactly two input iterators. 如果由于某种原因你不想使用itertools模块,那么编写你自己的迭代器就可以做同样的事情,至少如果你知道你正在处理两个输入迭代器。

def xzip2(i1, i2):
    i1, i2 = iter(i1), iter(i2)
    while True:
        yield next(i1), next(i2)

Actually, upon further reflection, it is not that hard to make it work with any number of iterators. 实际上,经过进一步反思,使其与任意数量的迭代器一起工作并不困难。 I am fairly sure itertools.izip must be implemented something like this. 我相当确定itertools.izip必须实现这样的东西。

def xzip(*iters):
    iters = [iter(i) for i in iters]
    while True:
        yield tuple([next(i) for i in iters])

(And looking at the documentation , I see it is, except they're using map rather than list comprehensions.) (看看文档 ,我看到它是,除了他们使用map而不是列表推导。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM