concat列表并在python中求和

时间:2016-10-22 23:58:18

标签: python-3.x

我有两个列表L1L2

L1 = [2,3,4,5,6,7,8,9]
L2 = [1,2]

我想从L3L1制作列表L2

L3 =  [3,5,4,5,6,7,8,9]

我做了一个功能,但它无法工作:

def mapp():
    for i in range(len(L1)):
        try:
            L3.append(L2[i] + L1[i])
        except:
            L3.append(L1[i])
    return L3'

1 个答案:

答案 0 :(得分:0)

如果我理解正确,你想要两个列表(L1和L2)并用匹配的索引求和元素。你可以这样做:

def mapp(L1,L2):
    #we make sure the first list is always the longest
    if len(L1)<len(L2):
        L1,L2 = L2,L1
    #we copy the longest list
    L3=L1.copy()
    #we add the short list elements to the long list elements
    for i,n in enumerate(L2):
        L3[i]+=n
    return L3

print(mapp(L1=[2,3,4,5,6,7,8,9],L2=[1,2]))

输出:[3, 5, 4, 5, 6, 7, 8, 9]