正在打印语句“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) = 2372208335176Hello 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) = 2372208335176Process finished with exit code 0
2 回答

开满天机
TA贡献1786条经验 获得超13个赞
在 Python 3 中,该zip
函数产生一个迭代器,它只能被消耗一次,你必须将它转换为 a list
:
zip_shop = list(zip(groceries, price))

郎朗坤
TA贡献1921条经验 获得超9个赞
您以错误的方式使用 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):
print("Hello before using list(zip_shop)")
print("List:",list(zip(groceries,price)))
for g, p in zip(groceries,price):
print("Hello after using list(zip_shop)")
添加回答
举报
0/150
提交
取消