Break a list into roughly equal sized pieces.
1 2 3 4 5 6 | def split_seq(seq, size):
newseq = []
splitsize = 1.0/size*len(seq)
for i in range(size):
newseq.append(seq[int(round(i*splitsize)):int(round((i+1)*splitsize))])
return newseq
|
Inspired by http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/425044
This requires that you know the length of the list beforehand, of course, so you can't use it with an arbitrary sequence as is. It's simple, but it's easy to create fencepost errors when implementing it.
>>> split_seq(range(10), 3)
[[0, 1, 2], [3, 4, 5, 6], [7, 8, 9]]
Naming suggestion. The second parameter, "size", would be better named "numPieces", since split_seq([]..., x) always returns a list with x pieces.
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]
[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]
All integer approach. Here is an all integer method that builds a list of ranges first, then splices the sequence.
alternate implementation using integers. This version uses integer math and distributes the remaindered items evenly over the first few splits.
again, an integer approach. def splitCeil(seq, m):
def splitFloor(seq, m):
Another approach using slicing for the calculation of the list lengths.
Here is a one-liner that has the following characteristics:
1) It gives the exact number of smaller sequences that are desired.
2) The lengths of the smaller sequences are as similar as can be.
3) The smaller sequences are not subsequences; the original sequence is sliced-and diced. But all the original elements are included; usually, having actual subsequences is less important (in my own experience) than having the right number of sequences and having them be of similar lengths.
Where seq is the original sequence and num is the desired number of subsequences:
[seq[i::num] for i in range(num)]
This issue is discussed in more detail on my blog.
Implementation using numpy.linspace method. Just specify the number of parts you want the array to be divided in to.The array will be divided in to parts with nearly equal size.
Example :