这里的想法是:我有一个类似于这样的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暗示它维护秩序,所以它应该是稳定的,不是吗?我该怎么做呢?
谢谢
发布于 2013-12-04 21:08:07
跟踪a共计:
total = 0
for key, value in month_dictionary.iteritems():
total += value
month_dictionary[key] = total排序不会受到影响;只有新的键才会添加到排序中。
演示:
>>> 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)])https://stackoverflow.com/questions/20385957
复制相似问题