为什么Python会在一个三重嵌套的for上抛出内存异常?

2024-03-28 16:30:36 发布

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

我正在写一个for循环的演示,它输出RGB光谱中所有可能的颜色。目的是帮助学生理解for循环是如何工作的。你知道吗

import csv

print("Started")

for_max = 256


with open('spectrum.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    spectrum = []
    head = ["R", "G", "B", "Hex"]
    spectrum.append(head)
    for r in range(0, for_max):
        for g in range(0, for_max):
            for b in range(0, for_max):
                r_hex = format(r, '02x')
                g_hex = format(g, '02x')
                b_hex = format(b, '02x')
                hex_string = str("#") + str(r_hex) + str(g_hex) + str(b_hex)
                spectrum.append([format(r, '03'), format(g, '03'), format(b, '03'), hex_string])
    writer.writerows(spectrum)
print("Finished")

不幸的是,我目前得到一个内存溢出。你知道吗

Traceback (most recent call last): File "C:/[...]/rgb_for.py", line 31, in MemoryError

我已经检查了最终列表是否小于Python列表的最大值,事实上确实如此。因此,是什么导致了这种情况?你知道吗


Tags: csvcsvfileinformatforstringrangehead
1条回答
网友
1楼 · 发布于 2024-03-28 16:30:36

构建列表然后将其全部转储到CSV中可以说是一种糟糕的做法。如果您的程序需要输出许多行,但中途失败了怎么办?只有在最后输出才会导致数据丢失。这种方法的计算量也更大,因为转储一个巨大的列表是一项相当艰巨的任务,所以执行起来需要更长的时间。你知道吗

更好的方法是在每行就绪时输出它。试试这个尺码

import csv

print("Started")

for_max = 256

with open('spectrum.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    out_list = []
    head = ["R", "G", "B", "Hex"]
    writer.writerow(head)
    for r in range(0, for_max):
        for g in range(0, for_max):
            for b in range(0, for_max):
                r_hex = format(r, '02x')
                g_hex = format(g, '02x')
                b_hex = format(b, '02x')
                hex_string = str("#") + str(r_hex) + str(g_hex) + str(b_hex)
                out_list = [format(r, '03'), format(g, '03'), format(b, '03'), hex_string]
                writer.writerow(out_list)
print("Finished")

这种方法的另一个好处是,您可以看到输出文件大小稳步增加!你知道吗

相关问题 更多 >