0

私は、何年にもわたって1か月あたりの発生を追跡するデータ構造を作成しようとしています。私はリストの辞書が最良の選択肢であると判断しました。この構造のようなものを作成したい(年:1か月あたりの発生を表す12個の整数のリスト):

yeardict = {
'2007':[0,1,2,0,3,4,1,3,4,0,6,3]
'2008':[0,1,2,0,3,4,1,3,5,0,6,3]
'2010':[7,1,3,0,2,6,0,6,1,8,1,4]
}

私は入力として、次のような辞書を使用しています。

monthdict = {
'2007-03':4,
'2007-05':2,
'2008-02':8
etc.
}

コードを2番目の辞書にループさせ、最初にキー(年)の最初の4文字に注意を払い、それが辞書にない場合は、リスト内の12か月の空白の値とともにそのキーを初期化します。形式:[0,0,0,0,0,0,0,0,0,0,0,0]次に、その月の位置のリストにある項目の値を値に変更します。年が辞書にある場合は、リスト内の項目をその月の値と等しくなるように設定したいだけです。私の質問は、辞書内のリスト内の特定のアイテムにアクセスして設定するにはどうすればよいですか。私はグーグルに特に役に立たない多くのエラーに遭遇しています。

これが私のコードです:

    yeardict = {}
    for key in sorted(monthdict):
        dyear = str(key)[0:4]
        dmonth = str(key)[5:]
        output += "year: "+dyear+" month: "+dmonth
        if dyear in yeardict:
            pass
#            yeardict[str(key)[0:4]][str(key)[5:]]=monthdict(key)                
        else:
            yeardict[str(key)[0:4]]=[0,0,0,0,0,0,0,0,0,0,0,0]
#            yeardict[int(dyear)][int(dmonth)]=monthdict(key)

コメントアウトされている2行は、実際に値を設定する場所であり、コードに追加すると2つのエラーのいずれかが発生します。1。「dict」は呼び出せません。2。KeyError:2009

何か明確にできるかどうか教えてください。ご覧いただきありがとうございます。

4

3 に答える 3

5

これが私がこれを書く方法です:

yeardict = {}
for key in monthdict:
    try:
        dyear, dmonth = map(int, key.split('-'))
    except Exception:
        continue  # you may want to log something about the format not matching
    if dyear not in yeardict:
        yeardict[dyear] = [0]*12
    yeardict[dyear][dmonth-1] = monthdict[key]

01日付形式の1月はそうではないと仮定したことに注意してください。そうでない場合は、最後の行の代わりに00使用してください。dmonthdmonth-1

于 2013-02-27T21:56:27.327 に答える
0
defaultlist = 12*[0]
years = {}
monthdict = {
'2007-03':4,
'2007-05':2,
'2008-02':8
}

for date, val in monthdict.items():
    (year, month) = date.split("-")
    occurences = list(years.get(year, defaultlist))
    occurences[int(month)-1] = val
    years[year] = occurences

実際に編集すると、defaultdictは役に立ちません。デフォルトのgetを実行し、そのリストのコピーを作成するための回答を書き直しました

于 2013-02-27T21:54:08.970 に答える
0

これはあなたが望む振る舞いをしていますか?

>>> yeardict = {}
>>> monthdict = {
... '2007-03':4,
... '2007-05':2,
... '2008-02':8 }
>>> for key in sorted(monthdict):
...     dyear = str(key)[0:4]
...     dmonth = str(key)[5:]
...     if dyear in yeardict:
...         yeardict[dyear][int(dmonth)-1]=monthdict[key]
...     else:
...         yeardict[dyear]=[0]*12
...         yeardict[dyear][int(dmonth)-1]=monthdict[key]
... 
>>> yeardict
{'2008': [0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], '2007': [0, 0, 4, 0, 2, 0, 0, 0, 0, 0, 0, 0]}
>>> 
于 2013-02-27T21:56:54.190 に答える