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
  • 4,408
  • 3
  • 22
  • 42
David542
  • 101,766
  • 154
  • 423
  • 727

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
  • 45,929
  • 8
  • 75
  • 99
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,152
  • 2
  • 9
  • 32
  • 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