python:我可以扩展range()方法的上限吗?

2024-04-18 01:42:54 发布

您现在位置:Python中文网/ 问答频道 /正文

range()函数的上限是什么?如何扩展它,或者说,最好的方法是:

for i in range(1,600851475143):

Tags: 方法函数inforrange
3条回答

range(1, 600851475143)希望在内存中生成一个非常大的列表,您将得到内存不足错误。要节省内存,请使用xrange而不是range。不幸的是,xrange不能处理大数(这是一个实现限制)示例(引发overflowerr):

for i in xrange(1, 600851475143):
  print i

使用range可以在间隔中有较大的最小值或最大值,如果它们的差异很小。示例:

^{pr2}$

输出:

[1606938044258990275541962092341162602522202993782792835301376L, 1606938044258990275541962092341162602522202993782792835301377L, 1606938044258990275541962092341162602522202993782792835301378L]

针对循环问题的原始解决方案:

def bigrange(a, b = None):
  if b is None:
    b = a
    a = 0
  while a < b:
    yield a
    a += 1

for i in bigrange(1, 600851475143):
  print i

一个不那么花哨的解决方案,即使循环体中有continue,它也能工作:

i = 1 - 1
while i < 600851475143 - 1:
  i += 1
  print i

你考虑过这么做吗?或者有什么特别需要range()的原因吗?在

x = 1
while x < 600851475143:
    // some code
    x += 1

pts的回答让我在xrange python文档中看到了这一点:

Note

xrange() is intended to be simple and fast. Implementations may impose restrictions to achieve this. The C implementation of Python restricts all arguments to native C longs (“short” Python integers), and also requires that the number of elements fit in a native C long. If a larger range is needed, an alternate version can be crafted using the itertools module: islice(count(start, step), (stop-start+step-1)//step)

看来这是c python的一个特殊限制。在

相关问题 更多 >