Python range()和zip()对象类型 [英] Python range() and zip() object type

查看:179
本文介绍了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 范围确实按照您的建议行事,返回名单。它们被更改为生成器类似的对象,这些对象按需生成元素,而不是将整个列表扩展为记忆。一个优点是它们在典型用例中的效率更高(例如迭代它们)。

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.

To将所有输出一次检索到熟悉的列表对象中,您可以简单地调用 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()对象类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆