【问题标题】:Why is my list mutating because of a print statement in Python? [duplicate]为什么我的列表会因为 Python 中的 print 语句而发生变化? [复制]
【发布时间】:2021-03-06 11:43:42
【问题描述】:

我正在进行一项 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)

为什么 medical_records 会发生变异?非常感谢您的洞察力!

【问题讨论】:

  • 你没有改变一个列表。你正在改变你的 zip 对象,它是一个迭代器,你使用 list(medical_records),它耗尽了迭代器

标签: python python-3.x


【解决方案1】:

我相信zip 返回一个迭代器。当你调用list(medical_records) 时,你会耗尽迭代器。这就是为什么调用 len(list(medical_records)) 没有结果,因为没有什么可以让步。

来源:https://docs.python.org/3.3/library/functions.html#zip

【讨论】:

    【解决方案2】:

    您应该首先将zip(insurance_costs, names) 保存到一个列表中,例如

    zipped_list = list(zip(insurance_costs, names))

    然后对zipped_list 变量执行其他操作,在该变量下存储一个列表。 zip 只创建一个迭代器,它被第一个运行在它上面的函数耗尽。

    【讨论】:

      【解决方案3】:

      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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-25
        • 1970-01-01
        • 2020-09-30
        • 2022-01-15
        • 1970-01-01
        相关资源
        最近更新 更多