2014-02-10 2 views
1

이것은 연습 코드 Python Epiphanies입니다. 원래 질문 : 이 DICT을 수행하지만 정렬 된 순서로, 그리고 수율를 사용하지 않고 같은반복자가 키를 정렬 된 순서로 반환하는 dict의 하위 클래스를 디자인하십시오.

는, 그 반복자의 키를 반환 DICT의 서브 클래스를 디자인합니다. 표준 대답이 제공되지 않기 때문에 난 그냥이가 최적의 답 있는지 알고 싶어,

>>> 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 

:

나는 작동하는 것 같다 해결책을했다. 감사합니다. 당신은 단순히이 같은 __iter__에서 반복자를 반환 할 수

+1

코드가 작동하지 않습니다. 'self.it' 속성은 아무 것도하지 않고, 더 중요한 것은 같은 mydict에 대해 두 개의 독립적 인 반복자를 얻을 수 없다는 것입니다. – user2357112

답변

4

, SortedDict의 완전한 구현을위한

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.

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

dict 키로 반복기를 반환 할 수 있습니다.

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 
관련 문제