A better way to split up a list
Tim Chase
python.list at tim.thechases.com
Mon May 8 09:15:36 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 :)
It looks like there may be some problems with your code,
such that it doesn't "work fine"...particularly in lists
with 1, 2, or 3 elements.
The below "chopupmoves2" function does what you describe,
and is nice and short. A bunch of test-cases get generated
and compared so you can see their output. The
chopupmoves2() function regularly returns your described
results, while things seem a bit off with the chopupmoves()
HTH,
-tkc
from itertools import islice
def chopupmoves2(movelist):
size = len(movelist) / 3
return [
movelist[:size],
movelist[size:size*2],
movelist[size*2:]]
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
# test them with a bunch of test-cases
movelist =[]
for i in xrange(1,12):
movelist.append(i)
print "Movelist:", movelist
print "\toriginal:", chopupmoves(movelist)
print "\tTim's: ", chopupmoves2(movelist)
More information about the Python-list
mailing list