问题
I was wondering if there was a clear/concise way to add something to a set and check if it was added without 2x hashes & lookups.
this is what you might do, but it has 2x hash's of item
if item not in some_set: # <-- hash & lookup
some_set.add(item) # <-- hash & lookup, to check the item already is in the set
other_task()
This works with a single hash and lookup but is a bit ugly.
some_set_len = len(some_set)
some_set.add(item)
if some_set_len != len(some_set):
other_task()
Is there a better way to do this using Python's set api?
回答1:
I don't think there's a built-in way to do this. You could, of course, write your own function:
def do_add(s, x):
l = len(s)
s.add(x)
return len(s) != l
s = set()
print(do_add(s, 1))
print(do_add(s, 2))
print(do_add(s, 1))
print(do_add(s, 2))
print(do_add(s, 4))
Or, if you prefer cryptic one-liners:
def do_add(s, x):
return len(s) != (s.add(x) or len(s))
(This relies on the left-to-right evaluation order and on the fact that set.add() always returns None, which is falsey.)
All this aside, I would only consider doing this if the double hashing/lookup is demonstrably a performance bottleneck and if using a function is demonstrably faster.
来源:https://stackoverflow.com/questions/27427067/python-how-to-check-if-an-item-was-added-to-a-set-without-2x-hash-lookup