0

Suppose I have the following list:

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

Is there a one-liner that could be used to break this up into a list of n_chunks. For example:

chunk(l, 3)
[[1,2,3],[4,5,6],[7,8,9]]

So far I have:

>>> [l[len(l)*i//3:] for i in range(3)]
[[1, 2, 3, 4, 5, 6, 7, 8, 9], [4, 5, 6, 7, 8, 9], [7, 8, 9]]

Which works for the 'left side' of the range but not the right side.

funnydman
  • 9,083
  • 4
  • 40
  • 55
David542
  • 104,438
  • 178
  • 489
  • 842

2 Answers2

1

You can do this with numpy quite easily using np.array_split as long as len(l) is garanteed to be divisible by n:

import numpy as np
l = [1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> np.vstack(np.array_split(l, 3)).tolist()                                                                                                                                                                           
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]                                                                                                                                                                                  
sacuL
  • 49,704
  • 8
  • 81
  • 106
1

Try using np.split:

import numpy as np

l =np.array( [1, 2, 3, 4, 5, 6, 7, 8, 9] )
#if your array Len mod no_of_parts_to_split == 0
x=np.split(l, 3)
>>> print(x)
[array([1, 2, 3]), array([4, 5, 6]), array([7, 8, 9])]

#for any number of parts to split, for any length of array
n=4
y=np.split(l, range(0, len(l), len(l)//n)[1:])
>>> print(y)
[array([1, 2]), array([3, 4]), array([5, 6]), array([7, 8]), array([9])]
Grzegorz Skibinski
  • 12,624
  • 2
  • 11
  • 34
  • What seems to be wrong with my answer here? – Grzegorz Skibinski Feb 20 '20 at 21:14
  • I didn't downvote, but the question is a clear duplicate (some people downvote answers to questions that are clear duplicates, I personally believe that is harsh). Also, the question is *explicitely* about list objects, but this answer is about numpy.ndarray objects – juanpa.arrivillaga Feb 26 '20 at 20:25