Sook Yee Lim Sook Yee Lim - 3 years ago 111
Python Question

Given an index list and a list of list how to insert items in the list of list at that index?

I got this list of 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']]


and index list:

indexA=[2, 4, 5]


For example, at index two the sublist of a is [2, 0, 0, 15, 2, 'g'].I want to insert the numbers in this sublist into other sublists at index two.So the first number,2, goes into sublist a at index 2 and the next number in sublist g,0, goes into sublist c at index 2 and so on.
NOTE: when it reaches its own list,in this case sublist g, it skips the sublist and the number is skipped as well.So it continues inserting number 15 into sublist w.How do I do this?Thanks in advance.

EDIT: Only the numbers are inserted not the alphabet like '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']]

Answer Source

Check my comments and let me know if you need more explanation :

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

Output:

[[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']]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download