为什么我的列表会因为Python中的print语句而发生变化?[duplicate]

f87krz0w  于 2023-01-10  发布在  Python
关注(0)|答案(3)|浏览(143)
    • 此问题在此处已有答案**:

Why can't I iterate twice over the same iterator? How can I "reset" the iterator or reuse the data?(6个答案)
两年前关闭了。
我正在做一个CodeAcademy活动,我把两个列表压缩在一起,根据它们的排列顺序,我得到了不同的打印结果。

names = ["Mohamed", "Sara", "Xia", "Paul", "Valentina", "Jide", "Aaron", "Emily", "Nikita", "Paul"]
insurance_costs = [13262.0, 4816.0, 6839.0, 5054.0, 14724.0, 5360.0, 7640.0, 6072.0, 2750.0, 12064.0]

medical_records = zip(insurance_costs, names)

print (list(medical_records))

num_medical_records = len(list(medical_records))

print(num_medical_records)

当我打印时,我得到了预期的列表,但num_medical_records是0?如果我切换打印语句的顺序,结果是一个空列表,但打印num_medical_records给我正确的数字"11"。

medical_records = zip(insurance_costs, names)

num_medical_records = len(list(medical_records))

print (list(medical_records))

print(num_medical_records)

病历为什么会变异?非常感谢你的洞察力!

nom7f22z

nom7f22z1#

我相信zip会返回一个迭代器,当你调用list(medical_records)的时候,你会耗尽迭代器,这就是为什么调用len(list(medical_records))不会得到结果,因为没有东西可以产生。
Source: https://docs.python.org/3.3/library/functions.html#zip

wlwcrazw

wlwcrazw2#

您应该先将zip(insurance_costs, names)保存到列表中,例如
zipped_list = list(zip(insurance_costs, names))
然后在zipped_list变量上执行其他操作,在该变量下存储了一个列表。zip只创建一个迭代器,该迭代器在第一个函数运行时耗尽。

ldxq2e6h

ldxq2e6h3#

zip函数只能迭代一次。
你可以这样做:

names = ["Mohamed", "Sara", "Xia", "Paul", "Valentina", "Jide", "Aaron", "Emily", "Nikita", "Paul"]
insurance_costs = [13262.0, 4816.0, 6839.0, 5054.0, 14724.0, 5360.0, 7640.0, 6072.0, 2750.0, 12064.0]

medical_records = list(zip(insurance_costs, names))

print (medical_records)

num_medical_records = len(medical_records)

print(num_medical_records)

相关问题