Splitting a list

Paul McGuire ptmcg at austin.rr._bogus_.com
Tue Aug 31 10:33:36 EDT 2004


"Ian Sparks" <Ian.Sparks at etrials.com> wrote in message
news:mailman.2673.1093960462.5135.python-list at python.org...
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....



Maybe not the prettiest, but here's a solution using a generator (at least
you're avoiding a bunch of conversions to/from string).

-- Paul


l = [1,2,3,-1,4,5,-1,8,9]

def getSublists(lst, delim):
    loc = 0
    while loc < len(lst):
        try:
            nextloc = lst.index(delim,loc)
        except ValueError:
            nextloc = len(lst)
        yield lst[loc:nextloc]
        loc = nextloc+1

print [ sub for sub in getSublists(l,-1) ]









More information about the Python-list mailing list