default value for list access?

Ruslan Spivak rspivak at nuxeo.com
Sun Feb 27 15:31:11 EST 2005


В Вск, 27/02/2005 в 14:03 -0600, Bo Peng пишет:
> To clearify the problem:
> 
> The data is the count of something, for example a[90]=10. a may be a 
> dictionary if the range is huge and a list when the range is reasonably 
> small. In the dictionary case, I can use a.setdefault(80, 0) if key 80 
> does not exist. In the list case, I have to check the length of list 
> before I access it (or use exception).
> 
> This becomes troublesome when I need to do the following a lot.
> 
>    b = a[80][1] + a[80][2] + a[80][3]
> 
> If I use the getItem function in my previous email, it will look like
> 
>    b = getItem(getItem(a, 80, []), 1, 0) + getItem(getItem(a, 80, []), 
> 2, 0) + getItem(getItem(a, 80, []), 3, 0)
> 
> What would be the best solution to handle this? Something like
> 
>    b = df( a[80][1], 0) + df( a[80][2], 0) + df( a[80][3], 0)
> 
> would be reasonable but df can not be easily defined since the exception 
> will be raised before function df is called. Something like
> 
>    b = df( a, [80, 1], 0) + df( a, [80,2], 0) + df( a, [80, 3], 0)
> 
> would work if df is defined as
> 
> def df(a, idx, default):
>    try:
>      for i in range(0, idx):
>        a = a[ idx[i] ]
>      return a
>    except:
>      return 0
> 
> but I am afraid that a for loop would bring serious performance problem.
> 
> Thanks.
> 
> Bo

I'm not sure if that's suitable for you, but you could define your own
subclasses for 'dict' and 'list' and specify your specific behaviour you
would like.

For dict something like this:

class MyDict(dict):
    def __getitem__(self, key):
        try:
            return super(MyDict, self).__getitem__(key)
        except:
            return 0

a = MyDcit()

Ruslan





More information about the Python-list mailing list