我想存儲數據[年] [月] =日在Python中使用哪種數據結構來存儲這樣的數據?
年份和月份都可以是字典的關鍵字。
像data [year] [month] .append(day)這樣的操作是可能的。
我想存儲數據[年] [月] =日在Python中使用哪種數據結構來存儲這樣的數據?
年份和月份都可以是字典的關鍵字。
像data [year] [month] .append(day)這樣的操作是可能的。
您可以使用嵌套的字典:
data[year] = {}
data[year][month] = [day]
爲了使這一點變得更容易,你可以用collections.defaultdict
:
from collections import defaultdict
data = defaultdict(dict)
data[year][month] = [day]
甚至:
def monthdict():
return defaultdict(list)
data = defaultdict(monthdict)
data[year][month].append(day)
演示後者結構:
>>> from collections import defaultdict
>>> def monthdict():
... return defaultdict(list)
...
>>> data = defaultdict(monthdict)
>>> data[2013][3].append(23)
>>> data
defaultdict(<function monthdict at 0x10c9d0500>, {2013: defaultdict(<type 'list'>, {3: [23]})})
你可以使用一個詞典的詞典嗎?
data = {'1972' : {
'01': ['a', 'list', 'of', 'things'],
'02': ['another', 'list', 'of', 'things'],
},
'1973' : {
'01': ['yet', 'another', 'list', 'of', 'things'],
},
}
>>> data['1972']['02']
['another', 'list', 'of', 'things']
>>> data['1972']['01'].append(42)
>>> data
{'1972': {'01': ['a', 'list', 'of', 'things', 42],
'02': ['another', 'list', 'of', 'things']},
'1973': {'01': ['yet', 'another', 'list', 'of', 'things']}}
所以使用字典... – enginefree 2013-03-23 17:01:03
然後使用嵌套字典嗎? – 2013-03-23 17:01:51