抛开这一切不谈,如果双重哈希/查找明显是性能瓶颈,并且如果使用函数明显更快,我才会考虑这样做.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 itemif 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? 解决方案 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) != ls = 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. 这篇关于Python:如何检查一个项目是否被添加到一个集合中,没有 2x(哈希,查找)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-27 00:54