Tuesday, June 4, 2013

Python: splitting a list into a number of roughly equal chunks

I used this solution, however, since I wanted to have a set number of chunks as opposed to chunks of a set length, the function ended up being slightly different:

def splitList(longList, chunkNumber):
    #Get the number of elements in a chunk we want
    n = int(math.floor(len(longList)/chunkNumber)) + 1
    print n, 'length of a chunk'
    return [longList[i:i+n] for i in range(0, len(longList), n)]

No comments:

Post a Comment