【问题标题】:for loop skipping sections of dictionary in pythonfor循环跳过python中的字典部分
【发布时间】:2014-12-14 13:40:49
【问题描述】:
GeoFigs =  {'Populus':0, 'Tristidia':1, 'Albus':2, 'Fortuna Major':3, 'Rubeus':4,
            'Acquisitio':5, 'Conjunctivo':6, 'Caput Draconis':7, 'Laetita':8, 'Carcer':9, 
            'Amissio':10, 'Puella':11, 'Fortuna Minor':12, 'Puer':13, 'Cauda Draconis':14, 'Via':15}
KeyGeo = dict.copy(GeoFigs)
for key in KeyGeo:
    print KeyGeo[key]
    keychange = KeyGeo[key]
    newValue = key
    del KeyGeo[key]
    KeyGeo[keychange] =  newValue

当我运行 for 循环时,它会跳过一些产生的键

(0, 'Populus'), (1, 'Tristidia'), ('Carcer', 9), (3, 'Fortuna Major'), (4, 'Rubeus'),
(5, 'Acquisitio'), (6, 'Conjunctivo'), (7, 'Caput Draconis'), ('Puer', 13), (10, 'Amissio'),
(11, 'Puella'), (12, 'Fortuna Minor'), (2, 'Albus'), (14, 'Cauda Draconis'), (15, 'Via'), ('Laetita', 8)]

知道为什么它只跳过第 3 和第 9 吗?

【问题讨论】:

  • 字典通常是基于散列的实现。因此,值的存储顺序可能并不总是相同。
  • 在迭代集合时,您正在从集合中删除元素。不要这样做。从不。

标签: python for-loop dictionary


【解决方案1】:

这里有两个问题:

  1. dict 中键的顺序未定义。如果您关心排序,请使用 OrderedDict 之类的内容。
  2. 您正在对dict 进行结构更改,同时对其进行迭代。见Modifying a Python dict while iterating over it

【讨论】:

    【解决方案2】:

    其他人已经解决了这个问题 - 您在迭代时正在更改 dict。在开始之前,您可以通过获取密钥副本来解决问题。在 python 2 和 3 中有点不同。在 python 2 中,keys 是一个列表:

    for key in KeyGeo.keys():
        ...
    

    在 python 3 中,keys 是一个迭代器,因此您必须在开始之前进行迭代

    for key in list(KeyGeo.keys()):
        ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-31
      • 1970-01-01
      • 2011-10-11
      • 2013-02-01
      • 2013-01-11
      • 2021-04-08
      • 1970-01-01
      相关资源
      最近更新 更多