鉴于:
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循环将会有一个IndexError
为ListB
具有两个条目相比,ListA?
您可以使用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]
如果您更喜欢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])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句