I have the following set of sets in Python (no element could occure more than one anywhere):
set_of_sets = {frozenset({"01", "02", "03"}),
frozenset({"04", "05", "06"}),
frozenset({"07", "08"}),
frozenset({"09", "10"}),
frozenset({"11"}),
frozenset({"12"}),
frozenset({"13"}),
frozenset({"14"}),
frozenset({"15"})}
Now, I want to figure out if any requested element is in the set of sets, and if so, what is the specific set (get all the elements of this set). I have got here so far:
if any("001" in subset for subset in set_of_sets):
print("Present:")
else:
print("Not Present")
But this doesn't give the found set itself. I could go for this option:
for subset in set_of_sets:
if "01" in subset:
print(subset)
but this doesn't handle the possibility of not founding the element in question, and given the nature of unique occurence of elements, this full iteration over the subsets is somewhat wasteful (in case we found the subset).
CodePudding user response:
You can write for example:
next(s for s in set_of_sets if "08" in s)
This will raise StopIteration if the item is not found.
As pointed out by Mark in a comment, the optional default argument for next could be used to avoid the exception if you want a result like None instead:
next((s for s in set_of_sets if "08" in s), None)
CodePudding user response:
If you correct "001" to "01", then it will print "Present:" in the first attempt.
CodePudding user response:
You can use list comprehension to just return a list of found items, since you're only going to find one, you can simply print found[0]. An empty list will hit the else block and print 'Not Present'
found = [subset for subset in set_of_sets if "13" in subset]
if found:
print("Present:")
print(found[0])
else:
print("Not Present")
