添加/总和两个不均匀长度的列表或元组

时间:2014-09-30 01:54:14

标签: python list sum tuples add

在Python中,是否有一种很好的方法可以添加/求和(或以其他方式组合)两个长度不均匀的列表?

e.g。给出了一些清单:

a = [1,2,3]
b = [1,2,3,4]

生成列表c

c = [2,4,6,4]

其中每个元素是ab的总和,将缺少的元素视为零?

3 个答案:

答案 0 :(得分:10)

是的,您可以使用itertools.zip_longest()

>>> from itertools import zip_longest
>>> a = [1, 2, 3]
>>> b = [1, 2, 3, 4]
>>> [x + y for x, y in zip_longest(a, b, fillvalue=0)]
[2, 4, 6, 4]

答案 1 :(得分:2)

以下是我使用的内容:

[ (ax or 0) + (bx or 0) for (ax, bx) in map(None, a, b) ]

其中n or 0 is used to coalesce None to zeromap(None, a, b) is used as a null-expanding version of zip

有问题吗?更好的答案?

答案 2 :(得分:0)

另一种选择:

In [1]: a = [1, 2, 3]
In [2]: b = [1, 2, 3, 4]
In [3]: [i+ii if i and ii else i or ii for (i,ii) in map(lambda x,y: (x,y),a,b)]
Out[3]: [2, 4, 6, 4]