这是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
由于没有提供标准答案,我只是想知道这是否是最佳答案。 谢谢。
您的代码不起作用。 'self.it'属性没有做任何事情,更重要的是,你不能在同一个'mydict'上得到两个独立的迭代器。 – user2357112