問題描述
我了解如何在 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() 對象類型的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!