How can I convert this
list = [a, b, c, d, e, f, g, h, i]
to this
list = [[a, b, c], [d, e, f], [g, h, i]]
I want to separate the objects to groups of three in each.
How can I convert this
list = [a, b, c, d, e, f, g, h, i]
to this
list = [[a, b, c], [d, e, f], [g, h, i]]
I want to separate the objects to groups of three in each.
Use the numpy reshape function, as so:
import numpy as np
l = np.array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'])
l.reshape(3,3)
This function should split any list into chunk of threes.
def chunks(l):
return [l[i:i + 3] for i in range(0, len(l), 3)]
If you want the longer version, here you go.
def chunks(l):
result = []
for i in range(0, len(l), 3):
result.append(l[i:i + 3])
return result
same as @Ian but make it list to answer the question
initial_state = [1,2,0,3,4,5,6,7,8]
l = np.array(initial_state)
ilist = l.reshape(3,3).tolist()
print(ilist)
[[1, 2, 0], [3, 4, 5], [6, 7, 8]]