Problem splitting a string

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sat Oct 15 07:01:42 EDT 2005


On Sat, 15 Oct 2005 10:51:41 +0200, Alex Martelli wrote:

> Steven D'Aprano <steve at REMOVETHIScyber.com.au> wrote:
>    ...
>> You can *almost* do that as a one-liner:
> 
> No 'almost' about it...
> 
>> L2 = [item.split('_') for item in mystr.split()]
>> 
>> except that gives a list like this:
>> 
>> [['this', 'NP'], ['is', 'VL'], ['funny', 'JJ']]
>> 
>> which needs flattening. 
> 
> ....because the flattening is easy:
> 
> [ x for x in y.split('_') for y in z.split(' ') ]


py> mystr = 'this_NP is_VL funny_JJ'
py> [x for x in y.split('_') for y in mystr.split(' ')]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'y' is not defined


This works, but isn't flattened:

py> [x for x in [y.split('_') for y in mystr.split(' ')]]
[['this', 'NP'], ['is', 'VL'], ['funny', 'JJ']]



-- 
Steven.




More information about the Python-list mailing list