Python(追加列表时内存错误)

2024-05-04 11:42:48 发布

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

我正在寻找一种方法,也许,修改这个函数,以便将数据附加到列表中不会产生内存错误。在

我有一个程序,逐行读取一个文件,并根据某些条件将此文件中的数据写入文本文件(该文件将有超过1000000行)。我有附加几个列表(它们很长)的函数,然后逐行将列表中的数据写入文本文件。在

如果文件达到最大行数(1000000),我将其拆分。它工作得很好,但是我需要下面的函数来附加一个额外的列表(我在本例中对它进行了修改),当我在else语句中将0追加到列表中时,它会产生一个内存错误。在

我使用64位操作系统,Windows10(RAM 16GB)并使用Python2.7(32位)-但拆分文件的方法通常对我有效,不需要更新任何内容,所以我想知道是否可以通过修改循环来解决问题。在

谢谢你的建议!在

# This function writes data to the lists based on the given conditions.*

def get_new_list(workbook, list_1, list_2, list_equal_values):


    worksheet1 = workbook.sheet_by_name('SomeWorksheet')

    list_11 = []
    list_22 = []
    list_new_values = []

    # Get data from the worksheet and append to the lists.
    for row in range(1, worksheet1.nrows):
        value_11 = worksheet1.cell(row, 0).value
        value_22 = worksheet1.cell(row, 1).value
        new_value = worksheet1.cell(row, 10).value

        list_11.append(value_11)
        list_22.append(value_22)
        list_new_values.append(new_value)


    # Compare values from list_1, list_2 to values in list_11 and list_22.
    for index in range(len(list_1)):
        for i in range(len(list_11)):
            if str(list_1[index]) == str(list_11[i]) \
               and str(list_2 [index]) == str(list_22[i]):
                 value = list_new_values[i]
                 list_equal_values.insert(index, value)

            elif str(list_1[index]) == str(list_11[i]) \
                  and str(list_2 [index]) != str(list_22[i]):
                          value = list_new_values[i]
                         list_equal_values (index, value)

            **else:
            # He is the problem, Memory Error, but I need to append 0 
            # if the  first two conditions are not met**
                 list_equal_values.append(0)

    return list_equal_values
        # I empty the lists in case the file is split and new data is sent to this     function.
    del list_11[:]
    del list_22[:]
    del list_new_values[:]

Tags: and文件thetoin列表newindex
1条回答
网友
1楼 · 发布于 2024-05-04 11:42:48

问题不在于你的for循环。你的阵列越来越大。尝试删除所有不必要的数组或附件,以提高内存效率。在

如果不可能,可以尝试将部分结果存储在文件中,但这可能会很混乱。在

如果你想要一个简单的解决方案,我记得我以前也遇到过类似的问题。经过大量的研究,我发现如果我切换到Python2.7(64位)。。。问题解决了!在

希望有帮助!我记得我花了很多时间来弄清楚这一点,所以不要犯同样的错误

相关问题 更多 >