Separating elements from a list according to preceding element

Ben Cartwright bencvt at gmail.com
Sun Mar 5 15:11:43 EST 2006


Rob Cowie wrote:
> 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?

Maybe.  You could write a couple regexes, one to find the included
tags, and one for the excluded, then run re.findall on them both.

But there's nothing fundamentally wrong with your method.

> If this method is
> suitable, how might I implement it?

  tags = ['tag1', '+', 'tag2', '+', 'tag3', '-', 'tag4']

  include, exclude = [], []
  op = '+'
  for cur in tags:
      if cur in '+-':
          op = cur
      else:
          if op == '+':
              include.append(cur)
          else:
              exclude.append(cur)

--Ben




More information about the Python-list mailing list