A better way to split up a list

Tim Chase python.list at tim.thechases.com
Mon May 8 10:40:24 EDT 2006


> Argh, embarassment on my part due to incomplete spec.
> movelist is used to store a list of chess moves and
> splitting it up in this way is so it can be printed in a
> space that is 3 lines high but quite wide. Thus the way
> the list grows as it is appended to in chopupmoves is
> intended.

Perhaps the following was what you mean?

def chop(movelist, columns=3):
     result = []
     itemsInColumn = (columns+len(movelist)-1)/columns
     for i in range(columns):
         result.append(movelist[
             i*itemsInColumn:
             (i+1)*itemsInColumn])
     return result
# exercise the function:
for i in xrange(30):
     moves = range(1,i+1)
     print chop(moves)
     print chop(moves, 4)

This is a fairly generic columnization routine that will 
track overflow nicely.

-tkc







More information about the Python-list mailing list