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)
range(1, 600851475143)
希望在内存中生成一个非常大的列表,您将得到内存不足错误。要节省内存,请使用xrange
而不是range
。不幸的是,xrange
不能处理大数(这是一个实现限制)示例(引发overflowerr):使用
^{pr2}$range
可以在间隔中有较大的最小值或最大值,如果它们的差异很小。示例:输出:
针对循环问题的原始解决方案:
一个不那么花哨的解决方案,即使循环体中有
continue
,它也能工作:你考虑过这么做吗?或者有什么特别需要
range()
的原因吗?在pts的回答让我在xrange python文档中看到了这一点:
看来这是c python的一个特殊限制。在
相关问题 更多 >
编程相关推荐