Splitting a list

Ian Sparks Ian.Sparks at etrials.com
Tue Aug 31 15:25:27 EDT 2004


> Elaine Jackson wrote...
> def indices(x,y):
>     if y in x:
>         i = x.index(y)
>         j = i+1
>         return [i]+[z+j for z in indices(x[j:],y)]
>     return []
> 
> def listSplit(x,y):
>     z = [-1] + indices(x,y) + [len(x)]
>     return [x[z[i]+1:z[i+1]] for i in range(len(z)-1)]
> 

Thanks Elaine but so far I like Jeff Eplers version the best :

    def split(it, elem):
        l = []
        for i in it:
            if i == elem:
                yield l
                l = []
            else:
                l.append(i)
        yield l

>>> l = [1,2,3,-1,4,5,-1,8,9]
>>> list(split(l, -1))
[[1, 2, 3], [4, 5], [8, 9]]



More information about the Python-list mailing list