Python range() and zip() object type(Python range() 和 zip() 对象类型)
问题描述
我了解如何在 for 循环中使用 range() 和 zip() 等函数.但是我希望 range() 输出一个列表 - 很像 unix shell 中的 seq .如果我运行以下代码:
I understand how functions like range() and zip() can be used in a for loop. However I expected range() to output a list - much like seq in the unix shell. If I run the following code:
a=range(10)
print(a)
输出是range(10),表明它不是一个列表,而是一种不同类型的对象.zip() 在打印时有类似的行为,输出类似
The output is range(10), suggesting it's not a list but a different type of object. zip() has a similar behaviour when printed, outputting something like
<zip object at "hexadecimal number">
所以我的问题是它们是什么,制作它们有什么优势,以及如何在不循环它们的情况下将它们的输出输出到列表?
So my question is what are they, what advantages are there to making them this, and how can I get their output to lists without looping over them?
推荐答案
你必须使用 Python 3.
You must be using Python 3.
在 Python 2 中,对象 zip 和 range 确实按照您的建议行事,返回列表.它们已更改为类似 generator 的对象,这些对象按需生成元素,而不是将整个列表扩展为记忆.一个优势是在它们的典型用例中效率更高(例如迭代它们).
In Python 2, the objects zip and range did behave as you were suggesting, returning lists. They were changed to generator-like objects which produce the elements on demand rather than expand an entire list into memory. One advantage was greater efficiency in their typical use-cases (e.g. iterating over them).
惰性"版本也存在于 Python 2.x 中,但它们有不同的名称,即 xrange 和 itertools.izip.
The "lazy" versions also exist in Python 2.x, but they have different names i.e. xrange and itertools.izip.
要一次将所有输出检索到熟悉的列表对象中,您可以简单地调用 list 来迭代并使用内容:
To retrieve all the output at once into a familiar list object, you may simply call list to iterate and consume the contents:
>>> list(range(3))
[0, 1, 2]
>>> list(zip(range(3), 'abc'))
[(0, 'a'), (1, 'b'), (2, 'c')]
这篇关于Python range() 和 zip() 对象类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python range() 和 zip() 对象类型
基础教程推荐
- 包装空间模型 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
