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 等效项
基础教程推荐
猜你喜欢
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
