defaultdict equivalent for lists(列表的 defaultdict 等效项)
本文介绍了列表的 defaultdict 等效项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有你如何构建一个相当于 python 的非常有用的 collections.defaultdict
?
Is thereHow would you build an equivalent of python's very useful collections.defaultdict
?
这样一个容器的想象用法:
Imagined usage of such a container:
>>> a = collections.defaultlist(0)
>>> a[2]=7
>>> a[4]='x'
>>> a
[0,0,7,0,'x']
更新:我添加了一个跟进问题a> 为这个结构添加更多功能
UPDATE: I've added a follow up question to add even more functionality to this construct
推荐答案
我觉得这样用起来会有点混乱;但是,这是我对如何做到这一点的第一个想法:
I think this would be a bit confusing to use; however, here's my first thought on how to do it:
class defaultlist(list):
def __init__(self, fx):
self._fx = fx
def __setitem__(self, index, value):
while len(self) <= index:
self.append(self._fx())
list.__setitem__(self, index, value)
这需要一个可调用的(我认为 defaultdict 就是这样工作的)作为默认值.
This takes a callable (I think that's how defaultdict works) for the default value.
当我跑步时:
a = defaultlist(int)
print a
a[2] = 7
a[4] = 'x'
print a
我回来了:
[]
[0, 0, 7, 0, 'x']
这篇关于列表的 defaultdict 等效项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:列表的 defaultdict 等效项


基础教程推荐
猜你喜欢
- 求两个直方图的卷积 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 包装空间模型 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01