How to chop list n-elements at a time

Nils Hensel nils.hensel at online.de
Sat Jan 20 06:41:53 EST 2001


This is all I can come up with at this time of the morning ;o)

def bunch (mylist, times):
  copy = mylist [:]
  new = []
  while copy:
    item = []
    for i in range (times):
      try:
        item.append (copy.pop(0))
      except IndexError:
        item.append (None)
    new.append (item)
  return new

It does the job but I have the distinct feeling that it can be written
shorter using map() or something.
Hope it helps,
Nils


<cpsoct at my-deja.com> schrieb im Newsbeitrag
news:94bjs8$5nn$1 at nnrp1.deja.com...
> I've been at this a while and can't seem to get it to work. I am
> wondering if others know how, have tried, or already have written a
> func to package up list elements in sublists n at a time.
>
> I was able to get something that worked for bunches of 1, or 2, but i
> am wondering how to make the tool more general so that i could say:
>
> x=[1,2,3,4,5,6,7,8,9]
>
> bunch(x,1) --> [[1], [2], [3], [4], [5], [6], [7], [8], [9]]
> bunch(x, 2) --> [[1,2], [3,4], [5,6], [7,8], [9, None]
> bunch(x, 3) --> [[1,2,3], [4,5,6], [7,8,9]]
> bunch(x, 4) --> [1,2,3,4], [5,6,7,8] [9, None, None, None]]
>
>
> The algo. i was using for two at a time for example just tested for
> even and odd. but i am not sure how to do generalize to create the
> above.
>
> cheers,
> kevin parks
> cpsoct at lycos.com
>
>
>
>
>
> Sent via Deja.com
> http://www.deja.com/





More information about the Python-list mailing list