Separating elements from a list according to preceding element

Michael Spencer mahs at telcopartners.com
Sun Mar 5 18:48:04 EST 2006


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,
> examine what element precedes it and accordingly, insert it into the
> relevant list. However, I have not been successful.
> 
> Is there a better way that I have not considered? If this method is
> suitable, how might I implement it?
> 
> Thanks all,
> 
> Rob Cowie
> 
Since you're already using a regexp, why not modify it to group the operators
with their tags? :

 >>> import re
 >>> source = "tag1+tag2+tag3-tag4"
...
 >>> tagfinder = re.compile("([+-]?)(\w+)")
...
 >>> include = []
 >>> exclude = []
...
 >>> for op, tag in tagfinder.findall(source):
...     if op == "-":
...         exclude.append(tag)
...     else:
...         include.append(tag)
...
 >>> include
['tag1', 'tag2', 'tag3']
 >>> exclude
['tag4']
 >>>

(Example assumes that a tag can be matched by \w+ and that there
is no space between the operators and their tags)

Michael




More information about the Python-list mailing list