我正在根据索引号列表(indexNumberList)将数字列表(firstNumberList)插入另一个列表(secondNumberList)中的特定点。

indexNumberList = [1, 2, 5, 8]
firstNumberList = [0, 0, 0, 0]
secondNumberList = [ 3, 1, 3, 2, 4, 1, 1, 4, 4, 4, 9, 9, 12, 12, 18, 19, 18, 9]


我已经尝试了以下列表理解,但它返回[none, none, none, none]

result =[secondNumberlist.insert(indexNumberList[elem],firstNumberList[elem]) for elem in range(len(indexNumberList))]


最终输出应如下所示

[ 3, 0, 0, 1, 3, 0, 2, 4, 0, 1, 1, 4, 4, 4, 9, 9, 12, 12, 18, 19, 18, 9]

最佳答案

indexNumberList = [1, 2, 5, 8]
firstNumberList = [0, 0, 0, 0]
secondNumberList = [3, 1, 3, 2, 4, 1, 1, 4, 4, 4, 9, 9, 12, 12, 18, 19, 18, 9]

for i, v in zip(indexNumberList, firstNumberList):
    secondNumberList = secondNumberList[:i] + [v] + secondNumberList[i:]

print(secondNumberList)


印刷品:

[3, 0, 0, 1, 3, 0, 2, 4, 0, 1, 1, 4, 4, 4, 9, 9, 12, 12, 18, 19, 18, 9]


编辑:带有list.insert的版本(感谢@Chris_Rands):

for i, v in zip(indexNumberList, firstNumberList):
    secondNumberList.insert(i, v)

09-11 21:42