有没有更好的方法来编写循环列表,这样就不会产生内存错误?

2024-09-28 23:39:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下Python代码:

for i in range(0, len(oscillations) - sequence_length):
    a = patterns[i:i + sequence_length]
    b = oscillations[i:i + sequence_length]
    sequence_in = [a+b for a,b in zip(a,b)]
    sequence_out = oscillations[i + sequence_length]  
    network_input.append(sequence_in)
    network_output.append(sequence_out)

振荡的长度是212922。每个振荡元素的长度是25。模式的长度是完全相同的。两个列表的结构相同,但数据不同

上面的代码失败了,它给了我一个内存错误。有时在遍历循环时,有时在返回两个列表时

如果我把列表缩短到大约100000个元素,那么它就可以工作了

我知道这可能是我试图分配太多的内存,但我的问题是,是否有一种更聪明的方法来浏览我的列表,这样它就不需要分配那么多内存了


Tags: 内存代码in元素列表forlenrange
1条回答
网友
1楼 · 发布于 2024-09-28 23:39:24

正如一些评论者指出的,您可能不需要构建整个列表network_inputnetwork_output。内存消耗的最大改进是yield

def stuff(oscillations, sequence_length, patterns):
    for i in range(0, len(oscillations) - sequence_length):
        a = patterns[i:i + sequence_length]
        b = oscillations[i:i + sequence_length]
        sequence_in = [a + b for a, b in zip(a, b)]
        sequence_out = oscillations[i + sequence_length]
        yield (sequence_in, sequence_out)

for s in stuff(oscillations, sequence_length, patterns):
    print(s)

另一方面,通过注意多次对两个集合中的相同元素进行切片和求和,可以获得较小的改进ab在迭代之间只相差一个元素。您可以使用一个简单的移动和算法:

def moving_stuff(oscillations, sequence_length, patterns):
    ops = []
    sums = []
    for op in zip(oscillations, patterns):
        ops.append(op)
        if len(ops) > sequence_length:
            sequence_in = sums[:]
            sequence_out = op[0]
            yield (sequence_in, sequence_out)
            ops.pop(0)
            sums.pop(0)
        sums.append(sum(op))

相关问题 更多 >