Is there a standard class for an infinitely nested defaultdict?(无限嵌套的 defaultdict 是否有标准类?)
问题描述
有谁知道 Python 中是否有用于无限嵌套字典的标准类?
我发现自己在重复这种模式:
d = defaultdict(lambda: defaultdict(lambda: defaultdict(int)))d['abc']['def']['xyz'] += 1如果我想添加另一层"(例如d['abc']['def']['xyz']['wrt']
),我必须定义另一个嵌套defaultdicts.
为了概括这种模式,我编写了一个简单的类来覆盖 __getitem__
以自动创建下一个嵌套字典.
例如
d = InfiniteDict(('count',0),('total',0))d['abc']['def']['xyz'].count += 0.24d['abc']['def']['xyz'].total += 1d['abc']['def']['xyz']['wrt'].count += 0.143d['abc']['def']['xyz']['wrt'].total += 1
但是,有没有人知道这个想法的预先存在的实现?我试过谷歌搜索,但我不确定这会叫什么.
解决方案 您可以从 defaultdict
派生以获得您想要的行为:
class InfiniteDict(defaultdict):def __init__(self):defaultdict.__init__(self, self.__class__)类计数器(InfiniteDict):def __init__(self):InfiniteDict.__init__(self)self.count = 0self.total = 0定义显示(自我):打印%i 出 %i" % (self.count, self.total)
这个类的用法如下:
<预><代码>>>>d = 计数器()>>>d[1][2][3].total = 5>>>d[1][2][3].show()0 分(共 5 分)>>>d[5].show()0 出 0
Does anyone know if there's a standard class for an infinitely nestable dictionary in Python?
I'm finding myself repeating this pattern:
d = defaultdict(lambda: defaultdict(lambda: defaultdict(int)))
d['abc']['def']['xyz'] += 1
If I want to add "another layer" (e.g. d['abc']['def']['xyz']['wrt']
), I have to define another nesting of defaultdicts.
To generalize this pattern, I've written a simple class that overrides __getitem__
to automatically create the next nested dictionary.
e.g.
d = InfiniteDict(('count',0),('total',0))
d['abc']['def']['xyz'].count += 0.24
d['abc']['def']['xyz'].total += 1
d['abc']['def']['xyz']['wrt'].count += 0.143
d['abc']['def']['xyz']['wrt'].total += 1
However, does anyone know of a pre-existing implementation of this idea? I've tried Googling, but I'm not sure what this would be called.
You can derive from defaultdict
to get the behavior you want:
class InfiniteDict(defaultdict):
def __init__(self):
defaultdict.__init__(self, self.__class__)
class Counters(InfiniteDict):
def __init__(self):
InfiniteDict.__init__(self)
self.count = 0
self.total = 0
def show(self):
print "%i out of %i" % (self.count, self.total)
Usage of this class would look like this:
>>> d = Counters()
>>> d[1][2][3].total = 5
>>> d[1][2][3].show()
0 out of 5
>>> d[5].show()
0 out of 0
这篇关于无限嵌套的 defaultdict 是否有标准类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无限嵌套的 defaultdict 是否有标准类?
基础教程推荐
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 筛选NumPy数组 2022-01-01