Pythonic way to add a list of vectors

I am trying to create a method (sum) that takes a variable number of vectors and adds them. For educational purposes, I wrote my own class Vector, and the underlying data is stored in an instance variable with the data name.

My code for the sum @classmethodworks (for each of the transferred vectors, through each element in the data variable, and adds it to the list of results), but it seems non-pythonic, and wonders if there is a better way?

class Vector(object):
    def __init__(self, data):
        self.data = data

    @classmethod
    def sum(cls, *args):
        result = [0 for _ in range(len(args[0].data))]
        for v in args:
            if len(v.data) != len(result): raise
            for i, element in enumerate(v.data):
                result[i] += element

        return cls(result)
+4
source share
3 answers

itertools.izip_longest may come in handy in your situation:

a = [1, 2, 3, 4]
b = [1, 2, 3, 4, 5, 6]
c = [1, 2]

lists = (a, b, c)

result = [sum(el) for el in itertools.izip_longest(*lists, fillvalue=0)]

And here you got what you wanted:

>>> result
[3, 6, 6, 8, 5, 6]

, , 0. izip_longest(a, b) [(1, 1), (2, 2), (3, 0), (4, 0)]. .

, :

>>> lists
([1, 2, 3, 4], [1, 2, 3, 4, 5, 6], [1, 2])
>>> list(itertools.izip_longest(*lists, fillvalue=0))
[(1, 1, 1), (2, 2, 2), (3, 3, 0), (4, 4, 0), (0, 5, 0), (0, 6, 0)]

, , , .

+6

, ( "pythonic" ) __add__, + sum .

class Vector(object):
    def __init__(self, data):
        self.data = data

    def __add__(self, other):
        if isinstance(other, Vector):
            return Vector([s + o for s, o in zip(self.data, other.data)])
        if isinstance(other, int):
            return Vector([s + other for s in self.data])
        raise TypeError("can not add %s to vector" % other)

    def __radd__(self, other):
        return self.__add__(other)

    def __repr__(self):
        return "Vector(%r)" % self.data

Vector int, Vector " " __radd__, sum .

:

>>> v1 = Vector([1,2,3])
>>> v2 = Vector([4,5,6])
>>> v3 = Vector([7,8,9])
>>> v1 + v2 + v3
Vector([12, 15, 18])
>>> sum([v1,v2,v3])
Vector([12, 15, 18])
+5
args = [[1,   2,  3],
        [10, 20, 30],
        [7,   3, 15]]

result = [sum(data) for data in zip(*args)]
# [18, 25, 48]

, ?

+2
source

Source: https://habr.com/ru/post/1606162/


All Articles