defaultdict相当于列表 [英] defaultdict equivalent for lists

查看:117
本文介绍了defaultdict相当于列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有_如何建立等效的python非常有用的 集合.defaultdict



想象这种容器的使用:

 >>> a = collections.defaultlist(0)
>>>> a [2] = 7
>>>> a [4] ='x'
>>>> a
[0,07,0,'x']

UPDATE:我添加了一个后续问题以添加更多这个结构的功能

解决方案

我认为这会有点混乱的使用;然而,这里是我对如何做的第一个想法:

  class defaultlist(list):
def __init __ ,fx):
self._fx = fx

def __setitem __(self,index,value):
while len(self)< = index:
self .append(self._fx())
list .__ setitem __(self,index,value)



当我运行时:

  a = defaultlist(int)
print a
a [2] = 7
a [4] ='x'

我回来了:

  [] 
[0,0,7,0,'x']


Is there\How 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']

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)

This takes a callable (I think that's how defaultdict works) for the default value.

When I run:

a = defaultlist(int)
print a
a[2] = 7
a[4] = 'x'
print a

I get back:

[]
[0, 0, 7, 0, 'x']

这篇关于defaultdict相当于列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆