为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

翻翻过去那场雪 2021-07-28 17:49:56
正在打印语句“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))


查看完整回答
反对 回复 2021-08-03
?
郎朗坤

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


查看完整回答
反对 回复 2021-08-03
  • 2 回答
  • 0 关注
  • 151 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号