One may want to do the contrary of flattening a list of lists, like here: I was wondering how you can convert a flat list into a list of lists.
In numpy you could do
Another way to create a list of lists can be simplified as shown below:
>>>MyList = ['a','b','c','d','e','f']
# Calculate desired row/col
>>>row = 3
>>>col = 2
>>>NewList = [MyList[col*i : col*(i+1)] for i in range(row)]
>>>NewList
[['a', 'b', 'c'], ['d', 'e', 'f']]
This can method can be extended to produce any row and column size. If you select row and column values such that row*col >len(MyList)
, the sublist (row) containing the last value in MyList
will end there, and NewList
will simply be filled with the appropriate number of empty lists to satisfy the row/col specifications
>>>MyList = ['a','b','c','d','e','f','g','h']
>>>row = 3
>>>col = 3
>>>NewList = [MyList[col*i : col*(i+1)] for i in range(row)]
>>>NewList
[['a', 'b', 'c'], ['d', 'e', 'f'], ['g','h']]
>>>row = 4
>>>col = 4
>>>NewList = [MyList[col*i : col*(i+1)] for i in range(row)]
[['a', 'b', 'c', 'd'], ['e', 'f', 'g','h'], [], []]