Is there an easier way to break a list into sub groups

Elaine Jackson elainejackson7355 at home.com
Sun Feb 22 00:43:07 EST 2004


groups = lambda L,n: [L[i*n:(i+1)*n] for i in range(len(L)) if L[i*n:(i+1)*n]]

HTH


"MetalOne" <jcb at iteris.com> wrote in message
news:92c59a2c.0402212013.2e0fa89b at posting.google.com...
| The following does what I want, but I feel like this could maybe be a
| one liner.
| I just can't think of anything shorter.
| If there is nothing shorter, does this seem like a candidate for
| inclusion in the standard library somewhere.
|
| >>> def groups(l, n):
|       """l is an input list.
|          n is the size of the sub group
|          returns a list of the sub groups
|       """
| ...   i=0
| ...   g = []
| ...   while i < len(l):
| ...     g.append(l[i:i+n])  #append sub group to g
| ...     i+=n
| ...   return g
| ...
| >>> l = [1,2,3,4,5,6]
| >>> groups(l,2)
| [[1, 2], [3, 4], [5, 6]]
| >>> groups(l,3)
| [[1, 2, 3], [4, 5, 6]]
| >>> groups(l,4)
| [[1, 2, 3, 4], [5, 6]]





More information about the Python-list mailing list