A better way to split up a list

fidtz at clara.co.uk fidtz at clara.co.uk
Mon May 8 08:45:11 EDT 2006


The code below works fine, but it is less than nice to look at and
somewhat long winded. Is there a better way to do the docstring task?
This is the first working version, and can proabably be "compacted" a
bit (list comprehensions etc) but I am looking for a better basic
approach. Any help much appreciated :)

from itertools import islice
def chopupmoves(movelist):
    '''creates a list of 3 lists from one list, that should all have
(length of movelist)/3 length, with any remainder getting added to the
third list'''
    outputlist = [[],[],[]]

    parlen = int(len(movelist)/3)
    if parlen < 3:
        parlen = 3

    stoplist=[0];exit = 0
    while exit < len(movelist):
        stoplist.append(exit+parlen)
        exit = exit + parlen
    while len(stoplist) > 4:
        stoplist.pop(len(stoplist)-1)
    stoplist[-1]=len(movelist)

    for x in range(len(stoplist)-1):
        for i in islice(movelist,stoplist[x],stoplist[x+1],1):
            outputlist[x].append(i)
    return outputlist
movelist = [1,2,3,4,5,6,7,8,9,10,11]
print chopupmoves(movelist)




More information about the Python-list mailing list