Python 3范围与Python 2范围 [英] Python 3 range Vs Python 2 range
问题描述
我最近开始学习python3.
在 python 2 中,range()
函数可用于分配列表元素.
I recently started learning python 3.
In python 2 range()
function can be used to assign list elements.
>>> A = []
>>> A = range(0,6)
>>> print A
[0, 1, 2, 3, 4, 5]
在 python 3 中,当使用range()
函数时,这种情况正在发生
where as in python 3 when range()
function is used this is happening
>>> A = []
>>> A = range(0,6)
>>> print(A)
range(0, 6)
为什么会这样?
python为什么要进行此更改?
是恩赐还是祸根?
why is this happening?
why did python do this change?
Is it a boon or a bane ?
推荐答案
Python 3 使用 iterators 进行很多操作,其中 python 2 列表.文档提供了详细说明,包括更改为range
.
Python 3 uses iterators for a lot of things where python 2 used lists.The docs give a detailed explanation including the change to range
.
优点在于,如果您使用的是大范围迭代器或映射,则 Python 3 不需要分配内存. 例如
The advantage is that Python 3 doesn't need to allocate the memory if you're using a large range iterator or mapping. For example
for i in range(1000000000): print(i)
在python 3中需要少得多的内存. 如果您确实想让Python一次全部展开列表,则可以
requires a lot less memory in python 3. If you do happen to want Python to expand out the list all at once you can
list_of_range = list(range(10))
这篇关于Python 3范围与Python 2范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!