如何将一个列表中的所有整数添加到另一个列表中的整数,并在Python中以相同的顺序使用不同的长度?

Ang*_*ron 2 python numpy python-2.7

鉴于:

ListA = [1,2,3,4,5]

ListB = [10,20,30,40,50,60,70]

我如何使它这样ListC = [11,22,33,44,55,60,70],当C[0] = B[0] + A[0]...... C[5] = nil + B[5]等等?在这种情况下,我不能简单地用一个for循环将会有一个IndexErrorListB具有两个条目相比,ListA?

Psi*_*dom 7

你可以使用itertools.zip_longest(..., fillvalue=0):

from itertools import zip_longest
[x + y for x, y in zip_longest(ListA, ListB, fillvalue=0)]
# [11, 22, 33, 44, 55, 60, 70]

# or in python 2
from itertools import izip_longest
[x + y for x, y in izip_longest(ListA, ListB, fillvalue=0)]
# [11, 22, 33, 44, 55, 60, 70]
Run Code Online (Sandbox Code Playgroud)

如果您更喜欢numpy解决方案,可以使用numpy.pad将两个列表填充到相同的长度:

import numpy as np

def add_np(A, B):
    m = max(len(A), len(B))
    return np.pad(A, (0, m-len(A)), 'constant') + np.pad(B, (0, m-len(B)), 'constant')

add_np(ListA, ListB)
# array([11, 22, 33, 44, 55, 60, 70])
Run Code Online (Sandbox Code Playgroud)