处理Python中的大量数字

use*_*443 2 python

我们有需要遍历的号码"17179869184".但是当我们遍历列表时,我们得到了内存错误.无论如何我们可以处理类似的范围号码

for i in range(17179869184):
    print i

for i in xrange(17179869184):
    print i



Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    for i in xrange(17179869184):
OverflowError: Python int too large to convert to C long
Run Code Online (Sandbox Code Playgroud)

Ash*_*ary 6

你可以用itertools.countiter:

>>> from itertools import count
>>> c = count(0)
>>> for i in iter(c.next, 17179869184):
        #do something with i
Run Code Online (Sandbox Code Playgroud)

请注意,如果您只想循环那么多次,即您没有i在循环内使用,那么最好使用itertools.repeat:

>>> from itertools import repeat
>>> for _ in repeat(None, 17179869184):
...     # do something here
Run Code Online (Sandbox Code Playgroud)