Python 2.7.12 (default, Nov 202017, 18:23:56)
[GCC 5.4.020160609] on linux2
Type "help", "copyright", "credits" or "license"for more information.
>>> for i in xrange(1,3):
... print i
...12
>>> for i in range(1,3):
... print i
...12
>>> exit()
Python 3.5.2 (default, Nov 232017, 16:37:01)
[GCC 5.4.020160609] on linux
Type "help", "copyright", "credits" or "license"for more information.
>>> for i in xrange(1,3):
... print(i)
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'xrange' is not defined
>>> for i in range(1,3):
... print(i)
...12
确实会报错。。。
再看看两个的数据类型
Python2.7.12 (default, Nov 20 2017, 18:23:56)
[GCC5.4.020160609] on linux2
Type"help", "copyright", "credits" or "license" for more information.
>>> x = xrange(1,3)
>>> print type(x)
<type 'xrange'>
>>> x = range(1,3)
>>> print type(x)
<type 'list'>
哎呦。。。list数据类型是列表,那,xrange是啥咧?
上网查了下,xrange是返回一个生成器
如:
# python2>>> x = xrange(1,3)
>>> print x
xrange(1, 3)
>>> x = range(1,3)
>>> print x
[1, 2]
import time
sums = 0
x1 = time.clock()
for i in range(1, 100000000):
sums += 3*i
x2 = time.clock()
for i in xrange(1, 100000000):
sums += 3*i
x3 = time.clock()
print x2-x1, x3-x2
结果如下
12.074461 10.134922
速度上确实range稍逊一筹
在python3中将xrange取消了,
Python 3.5.2 (default, Nov 232017, 16:37:01)
[GCC 5.4.020160609] on linux
Type"help", "copyright", "credits"or"license"for more information.
>>> x = range(1,3)
>>> print(type(x))
<class 'range'>
>>>
同样的代码,在python3中的表现如何呢?
import time
sums = 0
x1 = time.clock()
for i in range(1, 100000000):
sums += 3*i
x2 = time.clock()
print(x2-x1)
最近几天改网上的代码(好吧,我只是个搬运工)。。。然后,有python2的代码xrange处在python3的地方报错,然后我改成了range不报错了,然后,实验室的妹子问起原因,然后,我。。。。。。于是,仔细查了查他们之间的区别先看结果:Python 2.7.12 (default, Nov 20 2017, 18:23:56) [GCC 5.4.0 20160609] on li