Skip to content Skip to sidebar Skip to footer

Inheriting List: Creating Division By Other Lists, Integers And Floats

I wanted to be able to divide entire lists by integers, floats, and other lists of equal length in Python, so I wrote the following little script. class divlist(list): def __in

Solution 1:

How can I write this in a simpler way?

By using self[i] instead of self.__cont_[i].

Do I really need the lines self.__cont_ and self.__len_?

No. Just use the regular methods of referring to a list, for example: [] and len().

As an aside, you might choose to have .__floordiv__() return a divlist instead of a list, so that you can continue to operate on the result.

classdivlist(list):
    def__floordiv__(self, other):
        """ Adds the ability to floor divide list's indices """if (isinstance(other, int) orisinstance(other, float)):
            return [i // other for i in self]
        elif (isinstance(other, list)):
            # DANGER: data loss if len(other) != len(self) !!return [i // j for i,j inzip(self, other)]
        else:
            raise ValueError('Must divide by list, int or float')

X = divlist([1,2,3,4])
assert X == [1, 2, 3, 4]
assert X // 2 == [0, 1, 1, 2]
assert X // [1,2,3,4] == [1, 1, 1, 1]
assert X // X == [1, 1, 1, 1]

Solution 2:

Instead of examining the explicit types of each argument, assume that either the second argument is iterable, or it is a suitable value as the denominator for //.

def__floordiv__(self, other):
    try:
        pairs = zip(self, other)
    except TypeError:
        pairs = ((x, other) for x in self)
    return [x // y for (x, y) in pairs]

You may want to check that self and other have the same length if the zip succeeds.

Post a Comment for "Inheriting List: Creating Division By Other Lists, Integers And Floats"