-1

I have a list as input, like this:

lst = [1, 10, 100, 2, 20, 200, 3, 30, 300]

Every three element is a subgroup, and I want to split them into subgroups, like this:

lst[0:3] # => [1,10,100]
lst[4:6] # => [2,20,200]
lst[7:9] # => [3,30,300]

What is the elegant way of doing it?

I only find this: Split list into smaller lists

I can certainly achieve this by the code about, but this falls short when the input comes with more arguments, like

lst = [1, 10, 100, 2, 20, 200, 3, 30, 300, 4, 40, 400, 5, 50, 500 ...]

I think maybe reshape() would be a good way?

Community
  • 1
  • 1
ZK Zhao
  • 19,885
  • 47
  • 132
  • 206

1 Answers1

4

With list comprehension:

[lst[i*3:(i+1)*3] for i in range(len(lst)//3)]
# [[1, 10, 100], [2, 20, 200], [3, 30, 300], [4, 40, 400], [5, 50, 500]]

If you need a reshape() function:

def reshape(lst, n):
    return [lst[i*n:(i+1)*n] for i in range(len(lst)//n)]
DainDwarf
  • 1,651
  • 10
  • 19
  • This solution losses data from the original list. Better use one of the linked solutions above. – FLC Jul 26 '23 at 14:21