2013-03-23 46 views

回答

2

您可以使用嵌套的字典:

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]})}) 
+0

我正在使用data = defaultdict(list),因此造成了一阵混乱。 – Hick 2013-03-23 17:05:20

+0

要继续这一点,如果我可以达到在双字典列表中的最里面的元素(或称为别的?)的遍历是Theta(n^3)正确吗?有没有更复杂的方法来存储这样的数据? Python是否提供更好的数据结构? – Hick 2013-03-23 17:09:12

+1

@Hick:不,“dict”访问只有O(1)。如果您搜索整个列表,那么对于列表长度n,就是O(n)。遍历日期列表完全是在不断的时间内完成的。 – 2013-03-23 17:10:07

1

你可以使用一个词典的词典吗?

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']}} 
相关问题