Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slicing a list into n nearly-equal-length partitions [duplicate]

Tags:

python

list

slice

I'm looking for a fast, clean, pythonic way to divide a list into exactly n nearly-equal partitions.

partition([1,2,3,4,5],5)->[[1],[2],[3],[4],[5]] partition([1,2,3,4,5],2)->[[1,2],[3,4,5]] (or [[1,2,3],[4,5]]) partition([1,2,3,4,5],3)->[[1,2],[3,4],[5]] (there are other ways to slice this one too) 

There are several answers in here Iteration over list slices that run very close to what I want, except they are focused on the size of the list, and I care about the number of the lists (some of them also pad with None). These are trivially converted, obviously, but I'm looking for a best practice.

Similarly, people have pointed out great solutions here How do you split a list into evenly sized chunks? for a very similar problem, but I'm more interested in the number of partitions than the specific size, as long as it's within 1. Again, this is trivially convertible, but I'm looking for a best practice.

like image 807
Drew Avatar asked Apr 17 '10 20:04

Drew


People also ask

How do you divide a list into N equal parts?

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.

Does slicing a list create a copy?

Slicing lists does not generate copies of the objects in the list; it just copies the references to them. That is the answer to the question as asked.


1 Answers

Just a different take, that only works if [[1,3,5],[2,4]] is an acceptable partition, in your example.

def partition ( lst, n ):     return [ lst[i::n] for i in xrange(n) ] 

This satisfies the example mentioned in @Daniel Stutzbach's example:

partition(range(105),10) # [[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100], # [1, 11, 21, 31, 41, 51, 61, 71, 81, 91, 101], # [2, 12, 22, 32, 42, 52, 62, 72, 82, 92, 102], # [3, 13, 23, 33, 43, 53, 63, 73, 83, 93, 103], # [4, 14, 24, 34, 44, 54, 64, 74, 84, 94, 104], # [5, 15, 25, 35, 45, 55, 65, 75, 85, 95], # [6, 16, 26, 36, 46, 56, 66, 76, 86, 96], # [7, 17, 27, 37, 47, 57, 67, 77, 87, 97], # [8, 18, 28, 38, 48, 58, 68, 78, 88, 98], # [9, 19, 29, 39, 49, 59, 69, 79, 89, 99]] 
like image 94
Manuel Zubieta Avatar answered Sep 20 '22 16:09

Manuel Zubieta