Python 字典大小最大限制

1 python dictionary memory-leaks

我试图了解以下 MemoryError 的原因。python中的字典是否有一些预定义的限制?

self.text 是从文件中读入的长字符串(大约 4.5 MB) L 等于 4641652

    L = len(self.text) 
    test = {}
    for i in xrange(L,0,-1):
        try:
            test[i] = self.text[i-1:]
        except MemoryError:
            print "Memory Error at the " + str(i) +"th iteration!"
            print sys.getsizeof(test)
            print len(test)
            exit()
Run Code Online (Sandbox Code Playgroud)

输出

Memory Error at the 4577890th iteration!
1573004
63762
Run Code Online (Sandbox Code Playgroud)

如果有帮助,我将在具有 16GB 内存的 Windows 机器上运行该程序。

Ric*_*ich 7

您正在循环中存储 1 + 2 + 3 + ... + 4641650 + 4641651 + 4641652... 字节。通过有问题的迭代,您已经进行了大约 63762 次,即 2032796322 字节。再来一条双线,瞧,您已经超过了 32 位整数限制,这对我来说似乎是遇到内存错误的合理位置。