Splitting a list
ptmcg at austin.rr._bogus_.com
Tue Aug 31 16:33:36 CEST 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?
>> l = [1,2,3,-1,4,5,-1,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
>> [[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).
l = [1,2,3,-1,4,5,-1,8,9]
def getSublists(lst, delim):
loc = 0
while loc < len(lst):
nextloc = lst.index(delim,loc)
nextloc = len(lst)
loc = nextloc+1
print [ sub for sub in getSublists(l,-1) ]
More information about the Python-list