gpt4 book ai didi

python - 累积一个 orderedDict

转载 作者:行者123 更新时间:2023-11-28 22:52:33 27 4
gpt4 key购买 nike

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

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

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

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

我一直在考虑这些问题,但显然需要一种方法来确定以前的 key 。

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

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

谢谢

最佳答案

跟踪总数:

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)])

关于python - 累积一个 orderedDict,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20385957/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com