Skip to main content
 首页 » 编程设计

python之Python 2 中奇怪的 xrange() 行为

2025年05月04日10kevingrace

我很熟悉 range() 和 xrange() 之间的区别。我注意到 xrange() 有一些奇怪的地方:

>>> xrange(1,10,2) 
xrange(1, 11, 2) 
 
>>> xrange(1,10,4) 
xrange(1, 13, 4) 

在功能上,它是正确的:

>>> for item in xrange(1,10,4): 
...     print item 
...  
1 
5 
9 
>>> 

但是,如您所见,返回的 xrange 对象中的停止值是上一个合法值之后的下一个更高值。有什么理由吗?

range() 现在在 Python 3 中提供与 Python 2 中的 xrange 相同的功能,其行为符合预期:

>>> range(1,10,4) 
range(1, 10, 4) 
>>> range(1,10,2) 
range(1, 10, 2) 
>>>  

请您参考如下方法:

range 的终止值或 xrange始终是排他性的。

引自docs ( python 2):

If step is positive, the last element is the largest start + i * step less than stop; if step is negative, the last element is the smallest start + i * step greater than stop.

对于 Python 3 :

For a positive step, the contents of a range r are determined by the formula r[i] = start + step*i where i >= 0 and r[i] < stop.

For a negative step, the contents of the range are still determined by the formula r[i] = start + step*i, but the constraints are i >= 0 and r[i] > stop.


关于您关于 repr() 的问题的第二部分的 xrange :

xrange(1, 10, 4)和 xrange(1, 13, 4)是相同的和repr()对于 native python 对象,通常会返回有效的 python 代码以重新创建对象。这不需要与最初创建对象的 python 代码完全相同。