Splitting a list
Michael J. Fromberger
Michael.J.Fromberger at Clothing.Dartmouth.EDU
Tue Aug 31 10:19:39 EDT 2004
In article <mailman.2673.1093960462.5135.python-list at python.org>,
"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....
How about this?
def split_list(L, brk):
last = -1
out = []
for pos in [ x for (x, y) in enumerate(L) if y == brk ]:
out.append(L[last + 1 : pos])
last = pos
out.append(L[last + 1:])
return out
-M
--
Michael J. Fromberger | Lecturer, Dept. of Computer Science
http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA
More information about the Python-list
mailing list