Home > Mobile >  Running lists/objects through class in python
Running lists/objects through class in python

Time:12-09

I currently have a working code that sets list values if the index is out of range:

import numpy as np

class Set_Value(list):
    def __getitem__(self, index):
        return super(Set_Value, self).__getitem__(index) if index >= 0 and index < len(self) else 1000

A=np.array([100,200,300,400])
S=Set_Value(A)
print(S[1])
print(S[-5])

As expected, the output of this code is:

print1: 200

print2: 1000

I would like to extend this to a list index, as follows:

X=[1,1,1,1,1,1,1,1,1,1]
Y=[1,1,1,-5,-5,-5,1,1,1,1]
print(S[X])
print(S[Y])

where the output of the code would be:

print1: [200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200]

print2: [200, 200, 200, 1000, 1000, 1000, 1000, 200, 200, 200, 200]

The whole point of doing this with a class was to avoid using loops. Whether or not that is actually a valid goal, at this point I am just curious and would like to see a working solution. I could not figure it out myself.

It might be possible that the class approach is not the best one to avoid using loops, but it was what I thought of.

CodePudding user response:

You should use class pattern matching like here:

import numpy as np

DEFAULT_VALUE = 1000

class Set_Value(list):
    def _get_item_with_default(self, index, default_value):
        return super(Set_Value, self).__getitem__(index) if index >= 0 and index < len(self) else default_value
    
    def __getitem__(self, index):
        if isinstance(index, int):
            return self._get_item_with_default(index, DEFAULT_VALUE)
        elif isinstance(index, list):
            return [self._get_item_with_default(elem, DEFAULT_VALUE) for elem in index]

This way you'd get the desired behaviour:

X=[1,1,1,1,1,1,1,1,1,1]
Y=[1,1,1,-5,-5,-5,1,1,1,1]
print(S[X])
print(S[Y])

output:

[200, 200, 200, 200, 200, 200, 200, 200, 200, 200]
[200, 200, 200, 1000, 1000, 1000, 200, 200, 200, 200]
  • Related