设计一个字典的子类,其迭代器将按排序顺序返回其键



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

由于没有提供标准答案,我只想知道这是否是最佳答案。谢谢。

你可以

简单地从__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

请检查此答案以获取SortedDict的完整实现。

您可以在字典键上返回迭代器。

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
def sorted_keys(dict):
    return 'n'.join(sorted(dict.keys()))
dict={'c':'c', 'b':'b', 'a':'a'}
print sorted_keys(dict)

最新更新