Simple List division problem

mensanator at aol.com mensanator at aol.com
Sat Jan 12 20:54:08 CET 2008


On Jan 12, 12:37 pm, marcstuart <marc.stuart.ris... at gmail.com> 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.,
> the overriding logic, is that I will get 3 lists and find a way for
> python to try to break it evenly, if not one list can have a greater
> amount of elements
>
> Would I use itertools ? How would I do this ?
>
> Thanks

def list_split(x,y):
  dm = divmod(len(x),y)
  if dm[1] != 0:
    z = [x[i*y:i*y+y] for i in xrange(len(x)/y) if len(x[i*y:])>=2*y]
    z.append(x[(len(x)/y-1)*y:])
  else:
    z = [x[i*y:i*y+y] for i in xrange(len(x)/y)]
  return z

>>> list_split([1,2,3,4,5,6,7,8,9,10],3)
[[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
>>> list_split([1,2,3,4,5,6,7,8,9,10],5)
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
>>> list_split([1,2,3,4,5,6,7,8,9,10],4)
[[1, 2, 3, 4], [5, 6, 7, 8, 9, 10]]
>>> list_split([1,2,3,4,5,6,7,8,9,10],2)
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]



More information about the Python-list mailing list