【问题标题】:OrderedDict Changing Order after Double Iterator Loop双迭代器循环后 OrderedDict 更改顺序
【发布时间】:2016-06-13 14:14:31
【问题描述】:

我设置了一个OrderedDict 并使用不同的语法执行字典推导,我已将其简化为一个函数dictcomp(fn, dictionary, key_or_value):

    x = OrderedDict(self._Median_Colors)
    x = self.dictcomp(hex2color, x, 'v')
    x = self.dictcomp(rgb_to_hsv, x, 'v_tuple')

此时我可以对字典进行排序:

    x = self.dictcomp(self.sort_by_hue, x, 'v')

到目前为止,一切似乎都结束了:

    print x

现在我需要重命名键,所以我将创建一个新的有序字典:

    color_indexes = list(xrange(0, len(x.keys())))
    print color_indexes

    newkeys = [self.rename(color_index) for color_index in color_indexes]

    print x.values()
    vi = iter(x.values())
    x = OrderedDict.fromkeys(newkeys);

我不知道如何立即填写旧值,所以我这样做了:

    ki = iter(x.keys())
    for k, v in zip(ki, vi):
        #print "k:", k
        print  v
        x[k] = tuple(v)

检查正常:

    print x.items()

麻烦来了:

    x = self.dictcomp(hsv_to_rgb, x, 'v_tuple')
    print x.items()

dictcomp 在哪里这样做:

    dictionary = {k: fn(*v) for k, v in dictionary.items()}

在哪里fn=hsv_to_rgb,dictionary=x

现在,我有:

[('Blue', (0.9764705882352941, 0.5529411764705883, 0.0)), ....

而不是预期的:

[('Red', (0.4745098039215686, 0.7372549019607844, 0.23137254901960794)), ....

键相同,但值已更改。我猜插入顺序受到了某种影响。这是怎么发生的?如何保持字典中键的顺序?

【问题讨论】:

    标签: python python-2.7 ordereddictionary


    【解决方案1】:

    问题是因为

    for i, j in zip([4, 5, 6], [1, 2, 3]):
        print i
        print j
    

    列中的结果:

    4 1 5 2 6 3

    事实证明,如果使用两个迭代器,zip 就像一个拉链。

    解决方法是将关键字值作为可迭代元组获取:

    for i in zip([4, 5, 6], [1, 2, 3]):
        print i
    

    返回

    (4, 1)
    (5, 2)
    (6, 3)
    

    【讨论】:

      猜你喜欢
      • 2011-10-24
      • 1970-01-01
      • 2013-05-18
      • 1970-01-01
      • 2021-10-29
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      相关资源
      最近更新 更多