Splitting a list
Andrea Griffini
agriff at tin.it
Wed Sep 1 02:04:17 EDT 2004
On Tue, 31 Aug 2004 09:54:17 -0400, "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?
Here are a few early-morning attempts :-)
def lsplit(L,sep):
try:
i = L.index(sep)
return [L[:i]] + lsplit(L[i+1:],sep)
except ValueError:
return [L]
def lsplit2(L,sep):
i = 0
res = []
while True:
try:
j = L.index(sep,i)
res.append(L[i:j])
i = j+1
except ValueError:
res.append(L[i:])
break
return res
def lsplit3(L,sep):
i = 0
while True:
try:
j = L.index(sep,i)
yield L[i:j]
i = j+1
except ValueError:
yield L[i:]
break
HTH
Andrea
More information about the Python-list
mailing list