Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python split list into n chunks

Tags:

python

I know this question has been covered many times but my requirement is different.

I have a list like: range(1, 26). I want to divide this list into a fixed number n. Assuming n = 6.

>>> x [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25] >>> l = [ x [i:i + 6] for i in range(0, len(x), 6) ] >>> l [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18], [19, 20, 21, 22, 23, 24], [25]] 

As you can see I didn't get 6 chunks (six sublists with elements of original list). How do I divide a list in such a way that I get exactly n chunks which may be even or uneven

like image 960
user110 Avatar asked Jun 30 '14 05:06

user110


People also ask

How do you split a list into N equal parts in Python?

To split a list into N parts of approximately equal length with Python, we can use list comprehension. We define the chunkify function to split the lst list into n chunks. To do this, we use list comprehension to return slices of list with from index i to the end with n items in each chunk.

How do you divide a list into N parts?

Method 1: Break a list into chunks of size N in Python using yield keyword. The yield keyword enables a function to come back where it left off when it is called again. This is the critical difference from a regular function.


1 Answers

Use numpy

>>> import numpy >>> x = range(25) >>> l = numpy.array_split(numpy.array(x),6) 

or

>>> import numpy >>> x = numpy.arange(25) >>> l = numpy.array_split(x,6); 

You can also use numpy.split but that one throws in error if the length is not exactly divisible.

like image 182
Jason Mitchell Avatar answered Sep 18 '22 23:09

Jason Mitchell