gpt4 book ai didi

python - Python 中的键控集合?

转载 作者:太空狗 更新时间:2023-10-29 23:55:54 27 4
gpt4 key购买 nike

有没有等价于KeyedCollection的在 Python 中,即元素具有(或动态生成)自己的键的集合?

即这里的目标是避免将 key 存储在两个地方,因此字典不太理想(因此出现问题)。

最佳答案

你可以很容易地模拟:

class KeyedObject(object):
def get_key(self):
raise NotImplementedError("You must subclass this before you can use it.")

class KeyedDict(dict):
def append(self, obj):
self[obj.get_key()] = obj

现在您可以使用 KeyedDict 而不是 dictKeyedObject 的子类(其中 get_key 返回一个有效的基于某些对象属性的键)。

关于python - Python 中的键控集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6780547/

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