A better way to split up a list
Larry Bates
larry.bates at websafe.com
Mon May 8 09:45:01 EDT 2006
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
>
> 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)
>
Try something like this:
def chopupmoves(movelist):
return [movelist[0:3], movelist[3:6], movelist[6:]]
-Larry Bates
More information about the Python-list
mailing list