Zip-Funktion Python - seltsames Verhalten [Duplikat]
Nov 10 2020
Gibt es eine Erklärung dafür, was unten passiert?
>>> foo = [10, 20]
>>> bar = [30, 40]
>>> foobar = zip(foo, bar)
>>> list(foobar)
[(10, 30), (20, 40)]
>>> tuple(foobar)
()
>>> list(foobar)
[]
>>> foobar
<zip object at 0x000001198D28E280>
Obwohl foobares sich immer noch um ein Zip-Objekt handelt, warum diese Ausgänge?
Antworten
DragonBobZ Nov 10 2020 at 00:57
zipist ein Generator und gibt einen Iterator zurück. Sobald es fertig ist, ist es das.
def mygen():
count = 10
while count:
yield count
count -= 1
gen_obj = mygen()
print(list(gen_obj))
print(list(gen_obj))
# [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
# []