2013-10-15 89 views
0

對於我正在處理的應用程序,我需要存儲一組項目以及與每個項目相關的概率。我也需要一致的列舉項目的方式,所以defaultdict不適合我的目的。迭代器定製'詞典與訂單'數據結構

當前我將項目存儲爲第一個槽中項目的元組列表,第二個中的項目概率。

mydata = zip(range(0,10), numpy.random.dirichlet([1]*10)) 

是數據結構的一個例子(雖然可以重複鍵,正如我所描述的)。

我打算把它包裝到一個類中,但我想更像是一個字典而不是一個列表來迭代它,而且我不確定如何去編寫這種類型的代碼。

例如,我希望能說這樣的話

tree = [[wt, [sym, ""]] for sym, wt in mydata.items()] 

(這個例子從羅塞塔代碼哈夫曼樹拍攝)。

是否有東西已經在Python中做了這件事,或者是我可以延伸的行爲?

+1

看一看[OrderedDict](http://docs.python.org/3.3/library/collections.html#collections.OrderedDict)。 – mouviciel

+0

如果我理解正確,你的'mydata'是一個2元組的列表,所以你可以用'tree = [[wt,[sym,「」]]爲sym,wt在mydata中迭代]'我猜。 –

+0

@JohannesCharra在我將它發送給解釋器時拋出一個ValueError,當我嘗試遍歷它時拋出一個AttributeError, –

回答

1
class MyIter(object): 
    def __init__(self, data): 
     self.data = data 
     self.idx = -1 

    def __iter__(self): 
     return self 

    def next(self): 
     if self.idx >= len(self.data) - 1: 
      raise StopIteration 

     self.idx += 1 
     return {self.data[self.idx][0]: self.data[self.idx][1]} 


mydata = zip(range(0,10), range(100,110)) 

for it in MyIter(mydata): 
    print it 

空運行:

Assuming mydata is: 
[(0, 100), (1, 101), (2, 102), (3, 103), (4, 104), (5, 105), 
(6, 106), (7, 107), (8, 108), (9, 109), (1, 101)] 

and the output is: 
{0: 100} 
{1: 101} 
{2: 102} 
{3: 103} 
{4: 104} 
{5: 105} 
{6: 106} 
{7: 107} 
{8: 108} 
{9: 109} 
{1: 101} # Note: Duplicate entry