猿问

使用“list(zip_variable)”后没有打印for循环中的语句

正在打印语句“Hello before using list(zip_shop)”。


语句“您好,使用 list(zip_shop)”后没有打印出来。


groceries = ["apple","chips","bread","icecream"]

price = [2,3,1.2,4.25]

print("groceries = ",groceries,"and price =",price)


zip_shop = zip(groceries,price)


print("zip_shop =", zip_shop,"and type(zip_shop) =",type(zip_shop),"and id(zip_shop) = ",id(zip_shop))

for g, p in zip_shop:

    print("Hello before using list(zip_shop)")



print("list(zip_shop)=", list(zip_shop),"and type(zip_shop) =",type(zip_shop),"and id(zip_shop) = ",id(zip_shop))

for g, p in zip_shop:

    print("Hello after using list(zip_shop)")

有人可以帮我理解这里的行为吗?


输出如下:


groceries =  ['apple', 'chips', 'bread', 'icecream'] and price = [2, 3, 1.2, 4.25]

zip_shop = <zip object at 0x0000022852A29948> and type(zip_shop) = <class 'zip'> and id(zip_shop) =  2372208335176

Hello before using list(zip_shop)

Hello before using list(zip_shop)

Hello before using list(zip_shop)

Hello before using list(zip_shop)

list(zip_shop)= [] and type(zip_shop) = <class 'zip'> and id(zip_shop) = 2372208335176


Process finished with exit code 0


翻翻过去那场雪
浏览 152回答 2
2回答

开满天机

在 Python 3 中,该zip函数产生一个迭代器,它只能被消耗一次,你必须将它转换为 a&nbsp;list:zip_shop&nbsp;=&nbsp;list(zip(groceries,&nbsp;price))

郎朗坤

您以错误的方式使用 zip 对象。Zip 对象迭代器是惰性求值的,这意味着它们仅在被调用时才求值,不会被求值多次,这避免了对 zip 对象的重复求值。当您想要迭代时,您必须为迭代对象调用 Zip()。groceries = ["apple","chips","bread","icecream"]price = [2,3,1.2,4.25]print("groceries = ",groceries,"and price =",price)#zip_shop = zip(groceries,price)for g, p in zip(groceries,price):&nbsp; &nbsp; print("Hello before using list(zip_shop)")print("List:",list(zip(groceries,price)))for g, p in zip(groceries,price):&nbsp; &nbsp; print("Hello after using list(zip_shop)")
随时随地看视频慕课网APP

相关分类

Python
我要回答