convert elements in list of lists by another list of lists

Question:

Hi there I have 2 list of lists as the example below:

list1=[['a','b','c'],
       ['d','e','f'],
       ['g','h','d'],
       ['n','m','j']]
list2 is list of lists of indice of list1
list2=[[0,2],
      [1,3]]
#output :
list2=[[['a','b','c'],['g','h','d']],
      [['d','e','f'],['n','m','j']]]

i want to convert elemnts of list2 by elements of list1 by thy indcies
thank you in advance

Asked By: elkamel

||

Answers:

This simple code works:

for lis in list2:
    for i in range(len(lis)):
        lis[i] = list1[lis[i]]

Another more convoluted version, that works for more depths of list embedding:

def lreplace(l2, l1):
    for obj in l2:
        if type(obj)==list:
            lreplace(obj, l1)
        else:
            l2[l2.index(obj)]=l1[obj]

list2 = [[[1],[0,0]],[3,2,3]]
lreplace(list2,list1)
list2
#Out[222]: 
#[[[['d', 'e', 'f']], [['a', 'b', 'c'], ['a', 'b', 'c']]],
# [['n', 'm', 'j'], ['g', 'h', 'd'], ['n', 'm', 'j']]]
Answered By: Swifty
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.