Simple List division problem
Fredrik Lundh
fredrik at pythonware.com
Sat Jan 12 14:33:50 EST 2008
marcstuart wrote:
> How do I divide a list into a set group of sublist's- if the list is
> not evenly dividable ? consider this example:
>
> x = [1,2,3,4,5,6,7,8,9,10]
> y = 3 # number of lists I want to break x into
> z = y/x
>
> what I would like to get is 3 sublists
>
> print z[0] = [1,2,3]
> print z[2] = [4,5,6]
> print z[3] = [7,8,9,10]
>
> obviously not even, one list will have 4 elements, the other 2 will
> have 3.,
here's one way to do it:
# chop it up
n = len(x) / y
z = [x[i:i+n] for i in xrange(0, len(x), n)]
# if the last piece is too short, add it to one before it
if len(z[-1]) < n and len(z) > 1:
z[-2].extend(z.pop(-1))
</F>
More information about the Python-list
mailing list