给定索引列表和列表列表如何在该索引的列表中插入项目?

时间:2017-10-01 08:19:00

标签: python list

我得到了这份清单:

a=[[0, 1, 1, 0, 'a'], [1, 0, 2, 0, 'c'], [2, 0, 0, 15, 2, 'g'], [1, 2, 0, 0, 'w'], [12, 0, 2, 3, 0, 2, 'front'], [0, 0, 0, 5, 2, 0, 'Z']]

和索引列表:

indexA=[2, 4, 5]

例如,在索引2处,a的子列表是[2,0,0,15,2,'g']。我想将此子列表中的数字插入到索引2处的其他子列表中。所以第一个数字,2,进入索引2的子列表a,子列表g,0中的下一个数字进入索引2的子列表c,依此类推。 注意:当它到达自己的列表时,在这种情况下子列表g,它会跳过子列表并跳过该数字。所以它继续将数字15插入子列表w。我该怎么做?提前感谢。

编辑:只插入数字,而不是像'g'那样插入字母。

Output: [[0, 1,2, 1,12,0,0 'a'], [1, 0,0, 2, 0,0 ,0'c'], [2, 0, 0, 15, 2,0,0'g'], [1, 2,15, 0,2, 0,0 'w'], [12, 0, 0,2, 0, 2,0 'front'], [0, 0, 0,0, 5, 0,0 'Z']]

1 个答案:

答案 0 :(得分:1)

检查我的评论,如果您需要更多解释,请告知我们:

a=[[0, 1, 1, 0, 'a'], [1, 0, 2, 0, 'c'], [2, 0, 0, 15, 2, 'g'], [1, 2, 0, 0, 'w'], [12, 0, 2, 3, 0, 2, 'front'], [0, 0, 0, 5, 2, 0, 'Z']]
index=[2, 4, 5]

for i in index:
    if(i<len(a)): # to check if index is within bounds
        for position,element in enumerate(a[i]):
            if isinstance(element,int) and i!=position and position<len(a): # i!=position to skip inserting in the same sublist
                a[position].insert(i,element)#insert(i,element) because the index the number is inserted follows the item in list index

输出:

[[0, 1, 2, 1, 12, 0, 0, 'a'], [1, 0, 0, 2, 0, 0, 0, 'c'], [2, 0, 0, 15, 2, 0, 2, 'g'], [1, 2, 15, 0, 2, 5, 0, 'w'], [12, 0, 2, 2, 3, 0, 0, 2, 'front'], [0, 0, 0, 5, 0, 2, 0, 'Z']]