Python 3 range Vs Python 2 range(Python 3 范围与 Python 2 范围)
问题描述
我最近开始学习python 3.
在 python 2 中,range()
函数可用于分配列表元素:
I recently started learning python 3.
In python 2 the 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()
函数输出如下:
But in python 3 the range()
function outputs this:
>>> 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 在 python 2 的很多地方使用 迭代器使用 lists.docs 给出了详细的解释,包括更改为 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 范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python 3 范围与 Python 2 范围
基础教程推荐
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 筛选NumPy数组 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01