How can I create a multidimensional list in Python?

advertisements

How can i create a multidimensional list while iterating through a 1d list based upon some condition.

I am iterating over a 1d list and whenever i find a '\n' i should append the so created list with a new list, for example,

 a = [1,2,3,4,5,'\n',6,7,8,9,0,'\n',3,45,6,7,2]

so I want it to be as,

new_list = [[1,2,3,4],[6,7,8,9,0],[3,45,6,7,2]]

how should i do it? Please help

def storeData(k):
    global dataList
    dlist = []
    for y in k:
        if y != '\n':
            dlist.append(y)
        else:
            break
    return dlist

This is what i have tried.


Using itertools.groupby would do the job (grouping by not being a linefeed):

import itertools

a = [1,2,3,4,5,'\n',6,7,8,9,0,'\n',3,45,6,7,2]

new_list = [list(x) for k,x in itertools.groupby(a,key=lambda x : x!='\n') if k]

print(new_list)

We compare the key truth value to filter out the occurrences of \n

result:

[[1, 2, 3, 4, 5], [6, 7, 8, 9, 0], [3, 45, 6, 7, 2]]