2014-02-10 38 views
1

這是Python Epiphanies的練習。原題:設計字典的子類,其迭代器按排序順序返回鍵

設計字典的一個子類,其迭代器將返回其密鑰,如 確實快譯通,但在有序和不使用產量

我這似乎工作的解決方案提出了:

>>> class mydict(dict): 
     def __iter__(self): 
      self.index = 0 
      self.sorted_keys = sorted(self.keys()) 
      self.it = iter(self.sorted_keys) 
      return self 
     def __next__(self): 
      if self.index < len(self.keys()): 
       self.index += 1 
       next(self.it) 
       return self.sorted_keys[self.index-1] 
      else: 
       raise StopIteration 


>>> d = mydict({2: 1, 4: 5, 3: 7, 1: 2}) 
>>> dit = iter(d) 
>>> next(dit) 
1 
>>> next(dit) 
2 
>>> next(dit) 
3 
>>> next(dit) 
4 
>>> next(dit) 
Traceback (most recent call last): 
    File "<pyshell#96>", line 1, in <module> 
    next(dit) 
    File "<pyshell#89>", line 13, in __next__ 
    raise StopIteration 
StopIteration 

由於沒有提供標準答案,我只是想知道這是否是最佳答案。 謝謝。

+1

您的代碼不起作用。 'self.it'屬性沒有做任何事情,更重要的是,你不能在同一個'mydict'上得到兩個獨立的迭代器。 – user2357112

回答

4

您可以簡單地返回從__iter__這樣一個迭代器,

class mydict(dict): 
    def __iter__(self): 
     return iter(sorted(super(mydict, self).__iter__())) 

d = mydict({2: 1, 4: 5, 3: 7, 1: 2}) 
dit = iter(d) 
print next(dit) # 1 
print next(dit) # 2 
print next(dit) # 3 
print next(dit) # 4 
print next(dit) # StopIteration 

請檢查this answer一個完整的實施SortedDict

0
def sorted_keys(dict): 
    return '\n'.join(sorted(dict.keys())) 
dict={'c':'c', 'b':'b', 'a':'a'} 
print sorted_keys(dict) 
1

您可以返回字典鍵上的迭代器。

class mydict(dict): 
    def __iter__(self): 
     return iter(sorted(self.keys())) 

>>> d = mydict({ 3: 1, 8:2, 4:3,2:2}) 
>>> for x in d: print x 
... 
2 
3 
4 
8