python2和python3中range()的使用区别

学习的网站是python2,我电脑上装的最新python3,所以学习到range的时候发现了不同。

python2代码:

L=range(0,10)
print(L)

结果

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

python3输入相同的代码其结果: range(0, 10)
如果想使用python3想显示和python2同样结果需要代码:
L=list(range(0,10))
print(L)

为什么产生这样的区别呢?

官网原话:

In many ways the object returned by range() behaves as if it is a list, but in fact it isn’t. It is an object which returns the successive items of the desired sequence when you iterate over it, but it doesn’t really make the list, thus saving space.

We say such an object is iterable, that is, suitable as a target for functions and constructs that expect something from which they can obtain successive items until the supply is exhausted. We have seen that the for statement is such an iterator. The function list() is another; it creates lists from iterables:

翻译:

可以看到上面这个很奇怪,在很多种情况下,range()函数返回的对象的行为都很像一个列表,但是它确实不是一个列表,它只是在迭代的情况下返回指定索引的值,但是它并不会在内存中真正产生一个列表对象,这样也是为了节约内存空间。

我们称这种对象是可迭代的,或者是可迭代对象,还有一种对象叫迭代器,它们需要从一个可迭代对象中连续获取指定索引的值,一直到索引结束。list()函数就是这样一个迭代器,它可以把range()函数返回的对象变成一个列表。

总结:python3中range返回的是其真实状态,是一个对象,为了让python3产生和python2中相同的效果,只需要多使用一个list()函数即可。

posted @ 2017-11-19 13:17  opw3n  阅读(700)  评论(0编辑  收藏  举报