Python:如何检查一个项目是否被添加到一个集合中,没有 2x(散列,查找)

2022-01-17 00:00:00 python python-3.x set

问题描述

我想知道是否有一种清晰/简洁的方法可以将某些内容添加到集合中,并检查它是否是在没​​有 2x 哈希的情况下添加的.查找.

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.

这是你可能会做的,但它有 2 倍的项目哈希

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()

有没有更好的方法使用 Python 的 set api 来做到这一点?

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) != 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))

(这取决于从左到右的评估顺序以及 set.add() 总是返回 None 的事实,这是错误的.)

(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.

相关文章