Search code examples
pythonstringlistnestednested-lists

How to merge list of strings into list of lists?


I have a list like this :

list_1 = ['2a', '3b', '2c', '2d', ... ]

and an another list like this :

list_2 = [[], [], [], ['3a'], ['3b']... ]

These two lists have the same size. I want to merge them to obtain a third one:

list_3 = [['2a'], ['3b'], ['2c','3a'], ['2d','3b']...]

I tried to use dataFrames to merge, I tried some differents loops but all I got is wrong. I tried some answers of similars questions but nothing I got with them is what I expect.

This is some examples I tried :

list_3 = list(product(list_1, list_2))
for i in list_2:
     for j in list_2:
         list_3 = list.append(str(i) + str(j))

list_3 =  [[str(list_1[x]) + str(x)] for x in list1,list_2]

The issues I get are :

list_3 = [['2a', '3b', '2c', '2d'...], [],[]....]
list_3 = [('2a', []), ('3b',[]), ('2c',['3a']), ...]

Have you any solutions ? If the answer already exists please link it.


Solution

  • I would ensure that both lists have the same length, then use their index to append to the new list. Simple solution using only list[index] and list comprehension:

    list_1 = ['2a', '3b', '2c', '2d']
    list_2 = [ [], [], ['3a'], ['3b'] ]
    
    if len(list_1) == len(list_2):
        new_list = [[list_1[i]] + list_2[i] for i in range(len(list_1))]
    print(new_list)
    

    Output

    [['2a'], ['3b'], ['2c', '3a'], ['2d', '3b']]