splitting a list into n groups

Paul Rubin http
Wed Oct 8 17:29:54 EDT 2003


Peter Otten <__peter__ at web.de> writes:
> > groups = [a[i:i+(len(a)//5)] for i in range(5)]
> 
> 
> >>> for k in range(10):
> ...     a = range(k)
> ...     print [a[i:i+(len(a)//5)] for i in range(5)]
> ...
> [[], [], [], [], []]
...
> Is that what you expected?

Bah!  Nope, got confused and mis-wrote the loop contents (started
thinking of donig it one way, then another, then got the two mixed up
while typing).  Also, wasn't concerned about the case where the list
can't be chopped into equal length parts.  Try this:

  assert len(a) > 0 and len(a) % 5 == 0
  d = len(a) // 5
  groups = [a[d*i:d*(i+1)] for i in range(5)]

Handling the case where the pieces end up unequal because len(a) isn't
a multiple of 5 gets a little messy:

    d = (len(a) + 4) // 5
    groups = [a[d*i:d*(i+1)] for i in range(5)]

when a = range(6) gives 

   [[0, 1], [2, 3], [4, 5], [], []] 

It's not clear to me whether that's good or bad: something like

  [[0, 1], [2], [3], [4], [5]]

is probably better, but that would depend on the application.




More information about the Python-list mailing list