Home > Enterprise >  How to merge list of strings into list of lists?
How to merge list of strings into list of lists?

Time:08-16

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.

CodePudding user response:

Just zip the lists and merge each tuple(str, list) using after changing the string to a list

list_3 = [[x]   z for x, z in zip(list_1, list_2)]

An alternative to zip is to iterate over the lists using enumerate

list_3 = [[x]   list_2[i] for i, x in enumerate(list_1)]

Output

print(list_3) # [['2a'], ['3b'], ['2c', '3a'], ['2d', '3b']]

CodePudding user response:

You want to pair stuff, don't double-loop or product anything

Use zip to iterate on both then build the merge

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

result = []
for value1, sublist2 in zip(list_1, list_2):
    result.append([value1]   sublist2)

print(result)
# [['2a'], ['3b'], ['2c', '3a'], ['2d', '3b']]

CodePudding user response:

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']]
  • Related