이것은 연습 코드 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__
에서 반복자를 반환 할 수
코드가 작동하지 않습니다. 'self.it' 속성은 아무 것도하지 않고, 더 중요한 것은 같은 mydict에 대해 두 개의 독립적 인 반복자를 얻을 수 없다는 것입니다. – user2357112