Separating elements from a list according to preceding element

Gerard Flanagan grflanagan at yahoo.co.uk
Sun Mar 5 16:28:58 EST 2006


James Stroud wrote:
> Gerard Flanagan wrote:
> > Rob Cowie wrote:
> >
> >>I'm having a bit of trouble with this so any help would be gratefully
> >>recieved...
> >>
> >>After splitting up a url I have a string of the form
> >>'tag1+tag2+tag3-tag4', or '-tag1-tag2' etc. The first tag will only be
> >>preceeded by an operator if it is a '-', if it is preceded by nothing,
> >>'+' is to be assumed.
> >>
> >>Using re.split, I can generate a list that looks thus:
> >>['tag1', '+', 'tag2', '+', 'tag3', '-', 'tag4']
> >>
> >>I wish to derive two lists - each containing either tags to be
> >>included, or tags to be excluded. My idea was to take an element,

[...]

> >
> > a = [ '+', 'tag1', '+', 'tag2', '-', 'tag3', '+', 'tag4' ]
> >
> > import itertools
> >
> > b = list(itertools.islice(a,0,8,2))
> > c = list(itertools.islice(a,1,8,2))
> >
> > result1 = [x[1] for x in itertools.izip(b,c) if x[0] == '+']
> > result2 = [x[1] for x in itertools.izip(b,c) if x[0] == '-']
> >
> > print
> > print result1
> > print result2
> >
> >
> > Gerard
> >
>
> Unfortunately this does not address the complete specification:
>
>  >>> a = [ 'tag1', '+', 'tag2', '-', 'tag3', '+', 'tag4' ]
>  >>>
>  >>> import itertools
>  >>>
>  >>> b = list(itertools.islice(a,0,len(a),2))
>  >>> c = list(itertools.islice(a,1,len(a),2))
>  >>>
>  >>> result1 = [x[1] for x in itertools.izip(b,c) if x[0] == '+']
>  >>> result2 = [x[1] for x in itertools.izip(b,c) if x[0] == '-']
>  >>>
>  >>> print
>
>  >>> print result1
> []
>  >>> print result2
> []
>
> Need to check for the absence of that first op.
> 
> James

Yes, should have stuck to the spec.

Gerard




More information about the Python-list mailing list