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

时间:2013-07-08 07:28:45

标签: python coding-style

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

[3, 0, 2, 1]
[8, 7]

预期结果:

[3, 0, 10, 8]

这些列表表示多项式系数

这是我的实施

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

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

5 个答案:

答案 0 :(得分: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]

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

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

答案 1 :(得分:2)

我认为简单的for循环比使用zip_longest ...

的理解简单得多
P = [3, 0, 2, 1]
Q = [8, 7]

A, B = sorted([P, Q], key=len)

for i, x in enumerate(reversed(A), 1):
   B[-i] += x

#print(B)

如果您需要保持P不变,请先复制它。此外,如果Q远小于P,则会更有效。

答案 2 :(得分:0)

您可以使用numpy

>>> import numpy as np
>>> L1 = [3, 0, 2, 1]
>>> L2 = [8, 7]
>>> L2 = [0 for i in range(len(L1)-len(L2))] + L2
>>> A1 = np.array(L1)
>>> A2 = np.array(L2)
>>> A1+A2
array([ 3,  0, 10,  8])

答案 3 :(得分:0)

a = [0, 1, 3, 4]

b = [5, 6]

iter_len = len(a)-(len(b) - 1)

for j in range(len(a), 0, -1):

        if j-iter_len < 0:
            break
        else:
            a[j-1] = a[j-1] + b[j-iter_len]
print a

答案 4 :(得分:0)

a = [1,2,3,4,5,6,7,8,9,10,5,7,9]

b = [1,2,5]

n = a

addStart = len(a) - len(b)

count = 0

for i in b :

    n[addStart+count] = i + a[addStart+count]
    count+=1
print n