为什么 Python 在三重嵌套上抛出内存异常?

Why is Python throwing a memory exception on a triple nested for?

我正在编写 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 列表最大值,确实如此。那么,可能是什么原因造成的?

构建列表然后将其完整转储到 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")

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