My code works but I feel like the while loop is possibly not as succinct as it could be.
Maybe using a while loop for a set of 2 items or less is silly? I’m not sure.
# <SETUP CODE TO SIMULATE MY SITUATION> import random import re # The real data set is much larger than this (Around 1,000 - 10,000 items): names = {"abc", "def", "123"} if random.randint(0, 3): # foo value is "foo" followed by a string of unknown digits: names.add("foo" + str(random.randint(0, 1000))) if random.randint(0, 3): # bar value is just "bar": names.add("bar") print("names:", names) matches = {name for name in names if re.match("foo|bar", name)} print("matches:", matches) # In the names variable, foo and/or bar may be missing, thus len(matches) should be 0-2: assert len(matches) <= 2, "Somehow got more than 2 matches" # </SETUP CODE TO SIMULATE MY SITUATION> foo, bar = None, None while matches: match = matches.pop() if match == "bar": bar = match else: foo = match print("foo:", foo) print("bar:", bar)
And here’s what else I’ve tried within the while loop:
-
I know ternaries don’t work like this (at least not in Python) but this is the pipe-dream level of simplicity I was hoping for:
(bar if match == "bar" else foo) = match
-
The remove function doesn’t return anything:
try: bar = matches.remove("bar") except KeyError: foo = matches.pop()