2

ここにアイデアがあります:私は次のようにorderedDictを持っています(簡略化):

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

私がやりたいことは、どういうわけかそれを反復することによってすべての値を蓄積することです。EG、最終結果をこれに似させたい(上記の例に基づく)

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

私はこれらの線に沿って何かを考えていましたが、明らかに以前のキーを決定する方法が必要です.

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

orderDict は順序を維持することを意味するため、これは悪い習慣ではないと思います。どうすればこれを行うことができますか?

ありがとうございました

4

1 に答える 1

4

合計を追跡する:

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)])
于 2013-12-04T21:08:07.530 に答える