【问题标题】:why does the dictionary key not update to record the change in keys为什么字典键不更新以记录键的变化
【发布时间】:2022-11-27 08:42:45
【问题描述】:

目标是将字典键增加 1,以便 for 循环生成的所有值都存储在字典中

代码

counting = {}
numbers = 1


for i in range(1, 11):
    counting[numbers] = (i)
    numbers + 1

print(counting)

但在最终结果中,字典只有一个键和一个存储值,即

运行代码的结果 {1:10}

我如何使键随每个循环而变化并存储所有生成的值

但在最终结果中,字典只有一个键和一个存储值,即

运行代码的结果 {1:10}

我如何使键随每个循环而变化并存储所有生成的值

【问题讨论】:

    标签: python dictionary basic


    【解决方案1】:

    如果要更新变量,则必须输入 numbers += 1numbers = numbers + 1 而不是 numbers + 1

    当 python 看到 numbers + 1 时,它只评估该行,得到 2,并且不对该值执行任何操作。如果没有 = 号,变量将不会改变。

    【讨论】:

      【解决方案2】:

      我认为您没有意识到,但是您的代码中存在一个愚蠢的拼写错误。将值分配给字典后,您增加了numbers 的计数,但没有分配它。所以,只需使用 += 赋值运算符。

      counting = {}
      numbers = 1
      
      
      for i in range(1, 11):
          counting[numbers] = (i)
          numbers += 1
      
      print(counting)
      

      开/关:

      {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10}
      

      【讨论】:

        猜你喜欢
        • 2013-03-04
        • 2014-08-04
        • 2023-04-11
        • 2013-09-13
        • 1970-01-01
        • 2012-01-07
        • 1970-01-01
        • 2019-04-24
        • 1970-01-01
        相关资源
        最近更新 更多