gpt4 book ai didi

python - 在没有mixin的情况下迭代类对象的字典 - python

转载 作者:行者123 更新时间:2023-11-28 21:22:20 25 4
gpt4 key购买 nike

该类的主要功能是一个以词为键id号为值的字典(注意:id不是连续的,因为删除了一些条目):

x = {'foo':0, 'bar':1, 'king':3}

当我为我创建的 customdict 类编写迭代器函数时,由于 KeyError,它在遍历 range(1 to infinity) 时中断。

class customdict():
def __init__(self,dic):
self.cdict = dic
self.inverse = {}

def keys(self):
# this is necessary when i try to overload the UserDict.Mixin
return self.cdict.values()

def __getitem__(self, valueid):
""" Iterator function of the inversed dictionary """
if self.inverse == {}:
self.inverse = {v:k for k,v in self.cdict.items()}
return self.inverse[valueid]

x = {'foo':0, 'bar':1, 'king':3}
y = customdict(x)

for i in y:
print i

如果没有 try and except 和访问 len(x),我如何解决 customdict 中字典的迭代> 类? 原因是 x 是 >>>,len(x) 对于实时来说会花费太长时间。

我试过 UserDict.DictMixin 突然它起作用了,为什么会这样?:

import UserDict.DictMixin
class customdict(UserDict.DictMixin):
...

有没有办法让我不使用 Mixin,因为不知何故在 __future__ 和 python3 中,mixins 看起来已被弃用?

最佳答案

定义以下方法。

def __iter__(self):
for k in self.keys():
yield k

I've tried UserDict.DictMixin and suddenly it works, why is that so?:

因为 DictMixin 为你定义了上面的 __iter__ 方法。( UserDict.py source code .)

关于python - 在没有mixin的情况下迭代类对象的字典 - python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19344046/

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