Python range() 和 zip() 对象类型

2022-01-10 00:00:00 python python-3.x list range iterator

问题描述

我了解如何在 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 中,对象 ziprange 确实按照您的建议行事,返回列表.它们已更改为类似 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 中,但它们有不同的名称,即 xrangeitertools.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')]

相关文章