Search code examples
pythoncsv3d2dimport-csv

Importing Excel list where every cell is a individual List python, 2d to 3d list


I have a CSV Excel file with a lot of rows. When I import it with csv.reader it converts it into a 2D-List where every Row is a single list. How do you break open those and convert every cell to a single list.

My Input:

[['1;2;3'],['Hello;How;areyou'],['test;1;2'],['4;5;6']]

aspired output:

[[[1],[2],[3]],[[Hello],[How],[areyou]],[[test],[1],[2]],[[4],[5],[6]]]

sorry if this question has been asked a lot, but i dont really find a solution for me.

Edit: There is something else I didnt notice when I looked in at the output. It is a 2D list and the items in the nested list are saved between highcommata like: [['1;2;3']]


Solution

  • I can't tell if your lists there are lists or strings since you have semi-columns delimiting them. Under the assumption they are a string you can use

    example = ["1;2;3","Hello;How;areyou","test;1;2","4;5;6"]
    desired = [[[elm] for elm in l.split(';')] for l in example]
    
    >>> [[['1'], ['2'], ['3']],
     [['Hello'], ['How'], ['areyou']],
     [['test'], ['1'], ['2']],
     [['4'], ['5'], ['6']]]
    

    if they are in fact 2d lists then the following gives what you want I think

    example = [[1,2,3],["Hello","How","areyou"],["test",1,2],[4,5,6]]
    desired = [[[elm] for elm in lst] for lst in example]
    
    >>> [[[1], [2], [3]],
     [['Hello'], ['How'], ['areyou']],
     [['test'], [1], [2]],
     [[4], [5], [6]]]
    

    have a read of https://www.programiz.com/python-programming/list-comprehension for some more examples of list comprehension to get these kind of results