gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:05:04 25 4
gpt4 key购买 nike

<分区>

这是来自 Python Epiphanies 的练习.原问题:

Design a subclass of dict whose iterator would return its keys, as does dict, but in sorted order, and without using yield.

我想出了一个似乎可行的解决方案:

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com