Separating elements from a list according to preceding element
James Stroud
jstroud at ucla.edu
Sun Mar 5 15:36:07 EST 2006
Bruno Desthuilliers wrote:
> Rob Cowie a écrit :
>
>> 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 you're responsible for the original URL, you may consider rewriting
> it this way:
> scheme://domain.tld/resource?tag1=1&tag2=1&tag3=1&tag4=0
>
> Else - and after you've finished cursing the guy that came out with such
> an innovative way to use url parameters - I think the first thing to do
> would be to fix the implicit-first-operator-mess, so you have something
> consistent:
>
> if the_list[0] != "-":
> the_list.insert(0, "+")
>
> Then a possible solution could be:
>
> todo = {'+' : [], '-' : []}
> for op, tag in zip(the_list[::2], the_list[1::2]):
> todo[op].append(tag)
>
> But there's surely something better...
Fabulous. Here is a fix:
the_list = ['+'] * (len(the_list) % 2) + the_list
todo = {'+' : [], '-' : []}
for op, tag in zip(the_list[::2], the_list[1::2]):
todo[op].append(tag)
More information about the Python-list
mailing list