-2

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.

  • 1
    Possible duplicate of [How do you split a list into evenly sized chunks?](https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks) – ggorlen Oct 26 '19 at 14:31

3 Answers3

1

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)
Ian
  • 3,605
  • 4
  • 31
  • 66
1

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
Vassilios
  • 493
  • 2
  • 10
0

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]]
Balki
  • 169
  • 2
  • 11