2014-02-10 32 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