split
Terry Reedy
tjreedy at udel.edu
Fri Aug 9 12:21:12 EDT 2002
"Emile van Sebille" <emile at fenx.com> wrote in message
news:PsO49.43097$7n5.8176 at sccrnsc01...
> Terry Reedy:
> > Another advertisement for the benefit of breaking long,
complicated
> > expressions into multiple lines and using temp variables ;-)
> Oh, but they're fun ;-)
>
> >>> y = [1,0,1,1,0,0,1,0]
> >>> [map(int, list(x)) for x in ''.join(map(str,y)).split('0')]
> [[1], [1, 1], [], [1], []]
This one is cute, instructive, and short and clear enough to grasp,
even though it only works for positie single-digit numbers.
>>> y=[22,0,33]
>>> [map(int, list(x)) for x in ''.join(map(str,y)).split('0')]
[[2, 2], [3, 3]]
As to the general problem. Here is a clear, comprehensible version of
the OPs lambda, with the added option of keeping or discarding empty
slices.
def seqsplit(seq, splitpoint = lambda x:x==' ', keepnull = False):
seqlen = len(seq)
splits = [i for i in range(seqlen) if splitpoint(seq[i])]
slices = zip([-1]+splits, splits+[seqlen])
return [seq[start+1:end] for start,end in slices if start+1 != end
or keepnull]
Much of the complication of the OP's version comes from using list
comprehensions as a substitute for using assignment statements (for
the two intermediate values seqlen and splits that are later used
twice). Ugh! If I used single char identifiers, seqsplit would also
be shorter than the lambda.
>>> seqsplit([1,0,1,1,0,0,1,0], lambda x: x == 0)
[[1], [1, 1], [1]]
>>> seqsplit([1,0,1,1,0,0,1,0], lambda x: x == 0, keepnull=True)
[[1], [1, 1], [], [1], []]
Terry J. Reedy
More information about the Python-list
mailing list