当您尝试创建一个包含前 232 个非负整数的列表时会发生这种情况(我在 Windows 10 系统上使用 Python 2.7.11):
>>> for i in range(2**32): pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: range() result has too many items
人们可能会期望,如果问题是内存中同时存在如此大量的项目,则解决方案可能是通过生成器一次处理一个项目......但事实并非如此:
>>> for i in xrange(2**32): pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: Python int too large to convert to C long
xrange()内置函数的文档解释了为什么会出现这个错误:
CPython 实现细节:xrange() 旨在简单快速。实现可能会施加限制来实现这一点。 Python 的 C 实现将所有参数限制为原生 C long(“短”Python 整数),并且还要求元素的数量适合原生 C long。
问题是 232 不能作为输入参数传递给 xrange,因为该数字大于 Python 中的最大“短”整数。试试这个来说服自己:
>>> import sys
>>> sys.maxint # 2**31 - 1
2147483647
>>> sys.maxint + 1 # 2**31 is automatically converted to "long" int
2147483648L
>>> 2**31
2147483648L
如果您需要重复执行计算超过 231 次(以下示例中为 234 次),您可以使用嵌套的 for 循环:
>>> loops = 0
>>> for i in xrange(2**4):
... for j in xrange(2**30):
... # do stuff
... loops += 1
...
>>> loops
17179869184L
>>> 2**34
17179869184L
上面的代码是一个相当幼稚的解决方法。 while 循环似乎是一个更合适的解决方案:
>>> loops = 0
>>> while loops < 2**34:
... # do stuff
... loops += 1
...
>>> loops
17179869184L