for循环中的语句在使用“ list(zip_variable)”之后不会被打印,但是在使用“ list(zip_variable)”之前会被打印

时间:2018-10-30 07:35:23

标签: python python-3.x

  

正在打印“在使用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

2 个答案:

答案 0 :(得分:2)

在Python 3中,zip函数产生一个迭代器,该迭代器只能被使用一次,您必须将其转换为list

zip_shop = list(zip(groceries, price))

答案 1 :(得分:0)

您以错误的方式使用了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)")