A better way to split up a list

John Machin sjmachin at lexicon.net
Mon May 8 09:24:45 EDT 2006


On 8/05/2006 10:45 PM, fidtz at clara.co.uk wrote:
> 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
What's this for? It causes weird things to happen with short lists.

> 
>     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)
> 

Unless I've totally misunderstood your spec, you don't need all that 
islice and stoplist stuff.

def chopupmoves2(movelist):
     parlen = len(movelist) // 3
     return [movelist[:parlen], movelist[parlen:parlen*2], 
movelist[parlen*2:]]

for k in range(13):
     mlist = range(k)
     print
     print "v1", chopupmoves(mlist)
     print "v2", chopupmoves2(mlist)




More information about the Python-list mailing list