Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
110 views
in Technique[技术] by (71.8m points)

python - zip variable empty after first use

Python 3.2

t = (1, 2, 3)
t2 = (5, 6, 7)
z = zip(t, t2)

for x in z:
    print(x)

Result:

(1, 5)
(2, 6)
(3, 7)

Putting in EXACTLY the same loop immediately after, nothing is printed:

for x in z:
    print(x)

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.

Is this how its supposed to work? There's no mention in the docs about this.

question from:https://stackoverflow.com/questions/66065571/understanding-iterators-and-zip-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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))

Note that in python3.x, a lot of the builtin functions now return iterators rather than lists (map, zip, filter)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...