問(wèn)題描述
Python 3.2
t = (1, 2, 3)
t2 = (5, 6, 7)
z = zip(t, t2)
for x in z:
print(x)
結(jié)果:
(1, 5)
(2, 6)
(3, 7)
之后立即放入完全相同的循環(huán),什么都不會(huì)打印:
Putting in EXACTLY the same loop immediately after, nothing is printed:
for x in z:
print(x)
z
仍然作為 <zip 對(duì)象存在于 0xa8d48ec>
.我什至可以重新分配 t
、t2
以再次壓縮,但它只能工作一次,而且只能工作一次.
z
still exists as <zip object at 0xa8d48ec>
. I can even reassign the t
, t2
to be zipped again, but then it only works once and only once, again.
這是它應(yīng)該如何工作的嗎?文檔中沒(méi)有提及這一點(diǎn).
Is this how its supposed to work? There's no mention in the docs about this.
推薦答案
這就是它在 python 3.x 中的工作方式.在 python2.x 中,zip
返回一個(gè)元組列表,但對(duì)于 python3.x,zip
的行為類似于 itertools.izip
在 python2.x 中的行為.要恢復(fù) python2.x 的行為,只需從 zip
的輸出中構(gòu)造一個(gè)列表:
That's how it works in python 3.x. In python2.x, zip
returned a list of tuples, but for python3.x, zip
behaves like itertools.izip
behaved in python2.x. To regain the python2.x behavior, just construct a list from zip
's output:
z = list(zip(t,t2))
請(qǐng)注意,在 python3.x 中,許多內(nèi)置函數(shù)現(xiàn)在返回迭代器而不是列表(map
、zip
、filter
)
Note that in python3.x, a lot of the builtin functions now return iterators rather than lists (map
, zip
, filter
)
這篇關(guān)于首次使用后 zip 變量為空的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!