【问题标题】:accumulating an orderedDict累积有序字典
【发布时间】:2013-12-21 13:33:09
【问题描述】:

想法是这样的:我有一个这样的orderedDict(简化):

{'012013': 3, '022013': 1, '032013': 5}

我想做的是通过以某种方式迭代来累积所有值。例如,我希望最终结果类似于此(基于上面的示例)

{'012013': 3, '022013': 4, '032013': 9}

我在考虑这些方面的事情,但显然需要一种方法来确定以前的键。

for key, value in month_dictionary.iteritems():
   month_dictionary[key] = month_dictionary[key] + month_dictionary[previous_key]

我认为这不是坏习惯,因为 orderedDict 暗示它维持秩序,所以它应该是稳定的,不是吗? 我该怎么做呢?

谢谢

【问题讨论】:

  • 只需将前一个键存储在一个变量中,而忽略项目中的第一个条目。
  • 你可以以此为借口升级到 Python 3:OrderedDict(zip(d, itertools.accumulate(d.values())))

标签: python python-2.7 ordereddictionary


【解决方案1】:

跟踪总数:

total = 0
for key, value in month_dictionary.iteritems():
    total += value
    month_dictionary[key] = total

订单不受影响;只有 new 键会添加到排序中。

演示:

>>> from collections import OrderedDict
>>> month_dictionary = OrderedDict((('012013', 3), ('022013', 1), ('032013', 5)))
>>> total = 0
>>> for key, value in month_dictionary.iteritems():
...     total += value
...     month_dictionary[key] = total
... 
>>> month_dictionary
OrderedDict([('012013', 3), ('022013', 4), ('032013', 9)])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-14
    • 2012-02-24
    • 1970-01-01
    • 1970-01-01
    • 2014-02-11
    • 1970-01-01
    • 2018-05-13
    • 2012-03-06
    相关资源
    最近更新 更多