range()
和 xrange()
可以处理10位数字,但是对于13位数字呢?我在论坛里没有找到任何相关信息。
range()
和 xrange()
可以处理10位数字,但是对于13位数字呢?我在论坛里没有找到任何相关信息。
import operator
def lrange(num1, num2 = None, step = 1):
op = operator.__lt__
if num2 is None:
num1, num2 = 0, num1
if num2 < num1:
if step > 0:
num1 = num2
op = operator.__gt__
elif step < 0:
num1 = num2
while op(num1, num2):
yield num1
num1 += step
>>> list(lrange(138264128374162347812634134, 138264128374162347812634140))
[138264128374162347812634134L, 138264128374162347812634135L, 138264128374162347812634136L, 138264128374162347812634137L, 138264128374162347812634138L, 138264128374162347812634139L]
另一个解决方案是使用itertools.islice
,正如在xrange
的文档中所建议的那样。
只要你不需要超过10的13次方的元素,创建范围就没有问题。
range(10**14,10**15,10**14)
提供
[100000000000000, 200000000000000, 300000000000000, 400000000000000, 500000000000000, 600000000000000, 700000000000000, 800000000000000, 900000000000000]
在64位Python环境下:
>>> xrange(9999999999999)
xrange(9999999999999)
对于一个13位数,我不会使用range()
函数。我的电脑无法容纳结果列表。
我认为这样做行不通。像len
这样的函数期望结果适合于4字节整数,因为cPython实现有限制。
在Python 3.0中:
>>> range(9999999999999)
range(0, 9999999999999)
看起来它能正常工作,但是...
>>> len(range(9999999999999))
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
len(range(9999999999999))
OverflowError: Python int too large to convert to C ssize_t
这里有一个相关问题,可以参考此处。
在Python的最新版本中,range()和xrange()都可以使用;但是,在2.5或更早的版本中,您需要解决int转换为long的问题。
def irange(start, stop=None, step=1):
if stop is None:
stop = long(start)
num = 1L
else:
stop = long(stop)
num = long(start)
step = long(step)
while num < stop:
yield num
num += step
这不是一个完整的解决方案(它不能处理负步长),但它应该能让你开始。
range(x) 返回一个列表。Python 列表不能包含那么多元素。如果需要执行数万亿次循环,应该使用 xrange() 进行迭代。
对于这个问题的解决方案,您不需要使用如此长的数字,因为您只需要质因数,可以使用平方根:
for i in xrange(2, int((n+1)**0.5)):
xrange
也不支持long
整数。例如:表达式xrange(sys.maxint, sys.maxint+10)
会引发OverflowError: Python int too large to convert to C long
异常。 - typeracer