在python中添加两个不同长度的列表,从右边开始

Tim*_*ung 7 python coding-style

我想从右边添加两个不同长度的列表这里是一个例子

[3, 0, 2, 1]
[8, 7]
Run Code Online (Sandbox Code Playgroud)

预期结果:

[3, 0, 10, 8]
Run Code Online (Sandbox Code Playgroud)

这些列表表示多项式的系数

这是我的实施

class Polynomial:
    def __init__(self, coefficients):
        self.coeffs = coefficients

    def coeff(self, i):
        return self.coeffs[-(i+1)]

    def add(self, other):
        p1 = len(self.coeffs)
        p2 = len(other.coeffs)
        diff = abs(p1 - p2)
        if p1 > p2:
            newV = [sum(i) for i in zip(self.coeffs, [0]*diff+other.coeffs)]
        else:
            newV = [sum(i) for i in zip([0]*diff+self.coeffs, other.coeffs)]                  
        return Polynomial(newV)

    def __add__(self, other):
        return self.add(other).coeffs
Run Code Online (Sandbox Code Playgroud)

这一个工作正常,只是想知道无论如何做更好,更清洁的代码?由于python总是在干净的代码上强调,我想知道有没有办法编写更干净的pythonic代码?

Joh*_*ooy 16

>>> P = [3, 0, 2, 1]
>>> Q = [8, 7]
>>> from itertools import izip_longest
>>> [x+y for x,y in izip_longest(reversed(P), reversed(Q), fillvalue=0)][::-1]
[3, 0, 10, 8]
Run Code Online (Sandbox Code Playgroud)

显然,如果你选择一个以相反的方式排序系数的约定,你可以使用

P = [1, 2, 0, 3]
Q = [7, 8]
[x+y for x,y in izip_longest(P, Q, fillvalue=0)]
Run Code Online (Sandbox Code Playgroud)