splitting a list into n groups

Corey Coughlin corey.coughlin at attbi.com
Wed Oct 8 19:40:23 EDT 2003


Rajarshi Guha <rajarshi at presidency.com> wrote in message news:<pan.2003.10.08.17.42.18.956301.22624 at presidency.com>...
> Hi,
>   is there an efficient (pythonic) way in which I could split a list into
> say 5 groups? By split I mean the the first x members would be one group,
> the next x members another group and so on 5 times. (Obviously x =
> lengthof list/5)
> 
> I have done this by a simple for loop and using indexes into the list.
> But it does'nt seemm very elegant
> 
> Thanks,

I had the same problem a while back.  Here's the function I wrote:

def GroupList(inlist, step=2):
    outlist = []
    ents = len(inlist)
    if ents % step != 0:
        print "In GroupList, the length of list ", inlist, " isn't
evenly"
        print "divisible by step %i" % step
        sys.exit(4)
    maininds = filter(lambda x: x % step == 0, range(ents))
    for i in maininds:
        currlist = []
        for j in range(step):
            currlist.append(inlist[i+j])
        outlist.append(currlist)
    return outlist

As you can see, I made some assumptions (the default n is 2, the list
must be evenly divisible by the step, and so on) and I haven't heavily
debugged it, but it might help you out.




More information about the Python-list mailing list