Reputation: 720
If I have a list of options that are being fed to a rest call like so:
[ 'allX', 'noX', 'noY', 'allY', 'var1', 'var2' ]
(The actual list is quite long)
Only one of '*X' can be included. Only one of '*Y' can be included. Any of the single item variables like var1 and var2 can be used with any combination of options.
Basically I wanna avoid a long kludge of if-then statements checking if allX and noX were provided together, ditto for the next pair, and so on.
Is there a handy python module for doing this or what is the most pythonic way of asserting this requirement? I have no control over the list itself, so tackling this from that end is not an option.
Thanks for any help.
Upvotes: 0
Views: 86
Reputation: 71471
To cut down on control statements, you can try this:
from itertools import groupby, chain
new_data = list(chain.from_iterable([[list(b)[0]] if a.isupper() else list(b) for a, b in groupby(s, key=lambda x: x[-1])]))
Output:
['allX', 'noY', 'var1', 'var2']
To make your algorithm as generic as possible, you can try this:
s = [ 'allX', 'noX', 'noY', 'allY', 'var1', 'var2' ]
import re
last = []
second_last = []
for i in s:
if re.findall("[A-Z]$", i):
if i[-1] not in second_last:
last.append(i)
second_last.append(i[-1])
else:
last.append(i)
print(last)
Output:
['allX', 'noY', 'var1', 'var2']
Upvotes: 3