1

I know how to convert a list of list to a flat list. For example,

import itertools
list_ = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
merged = list(itertools.chain.from_iterable(list_))
print(merged)
>> [1, 2, 3, 4, 5, 6, 7, 8, 9] 

Is it possible other way around? in this case, for a given flat list, is it possible to make a list of list contains three elements? I want to see the output like this

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

for a given input [1, 2, 3, 4, 5, 6, 7, 8, 9]

Mass17
  • 1,555
  • 2
  • 14
  • 29

1 Answers1

2

Just take slices:

a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [a[i:i+3] for i in range(0, len(a), 3)]

print(b)  # [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Or if you actually want to use numpy as the tag implies, use reshape() as suggested above

berardig
  • 652
  • 4
  • 10