Splitting a list

Alex Martelli aleaxit at yahoo.com
Wed Sep 1 03:32:30 EDT 2004


Ian Sparks <Ian.Sparks at etrials.com> wrote:

> string.split() is very useful, but what if I want to split a list of
integers on some element value?
> 
>  e.g. :
> 
> >> l = [1,2,3,-1,4,5,-1,8,9]
> >> l.split(-1)
> >> [[1,2,3],[4,5],[8,9]]
> 
> Here's my hideous first pass :
> 
> >> [[int(z) for z in x.split(',') if z] for x in ','.join([str(a) for a in
l]).split('-1')]
> >> [[1, 2, 3], [4, 5], [8, 9]]
> 
> When I see code like that I just know I've missed something obvious....

I think a simple generator might serve you well:

def isplit(seq, separator):
    result = []
    for item in seq:
        if item == separator:
            yield result
            result = []
        else:
            result.append(item)
    yield result

example use:

>>> list(isplit([1,2,3,-1,4,5,-1,8,9], -1))
[[1, 2, 3], [4, 5], [8, 9]]

Note that, the way isplit is coded, seq can be any iterable, not just a
list.  You may not need this little extra generality, but it can't
hurt...


Alex



More information about the Python-list mailing list