Home > Mobile >  Merging lists horizontally into a new list
Merging lists horizontally into a new list

Time:06-28

Python newbie here struggling with numpy.

I have 18 lists

L1 = [1,2,3,4]
L2 = [5,6,7,8]
L3 = [5,7,8,5]
..........
......
L18 = [6,4,7,8]

I want to merge them into a new list (lets say L_ALL), so that in a single row I have all the lists..(1 row, 18 columns with lists...)

I have tried

L_ALL = [L1,L2,....L18] 

but this merges them adding new rows, so I end up with a list with 18 rows.

Things like hstack, np.concatenate and sum do not help because they do something like:

L_ALL = [1,2,3,4,5,6,7,8,5,7....]

and I need the lists as separate lists in different columns (same row), not a single list (column) with all the elements.

Does this makes sense?

Thanks in advance

CodePudding user response:

  import pandas as pd
  L1 = [1,2,3,4]
  L2 = [5,6,7,8]
  L3 = [5,7,8,5]
  l_all = [[L1,L2,L3]]

  df = pd.DataFrame(l_all)

this creates a single row with as many columns as you have the list

Now if you do

 df.values[0]

you get

 array([list([1, 2, 3, 4]), list([5, 6, 7, 8]), list([5, 7, 8, 5])],
  dtype=object)

CodePudding user response:

You can try in this way

L1 = [1,2,3,4]
L2 = [5,6,7,8]
L3 = [5,7,8,5]
..........
......
L18 = [6,4,7,8]



finalList=['']
finalList.append(L1)
finalList.append(L2)
.
.
.
finalList.append(L18)

print(" ".join(map(str, finalList)))

You will get output as follows

[1, 2, 3, 4] [5, 6, 7, 8] [5,7,8,5] ... [6,4,7,8]
  • Related