我想存储数据[年] [月] =日在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