Python 2.x和Python 3.x对range()的定义是不一样的。Python 2.x里range返回的是一个list,而Python 3.x里range返回的是一个iterator。Python 3.x的range相当于Python 2.x里的xrange。iterator是动态返回元素的,而list则是普通的对象数组。
Python 2.7.7 (default, Jun 1 2014, 14:17:13) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> range(5)
[0, 1, 2, 3, 4]
Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> range(5)
range(0, 5)
>>> a = _
>>> dir(a)
["__class__", "__delattr__", "__doc__", "__eq__", "__format__", "__ge__", "__get
attribute__", "__getitem__", "__gt__", "__hash__", "__init__", "__iter__", "__le
__", "__len__", "__lt__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "_
_repr__", "__reversed__", "__setattr__", "__sizeof__", "__str__", "__subclasshoo
k__"]
>>> iter(a)
>>> b = _
>>> dir(b)
["__class__", "__delattr__", "__doc__", "__eq__", "__format__", "__ge__", "__get
attribute__", "__gt__", "__hash__", "__init__", "__iter__", "__le__", "__length_
hint__", "__lt__", "__ne__", "__new__", "__next__", "__reduce__", "__reduce_ex__
", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__"]
>>> next(b)
0
>>> next(b)
1
>>> next(b)
2
>>> next(b)
3
>>> next(b)
4
>>> next(b)
Traceback (most recent call last):
File "", line 1, in
StopIteration