Python: how to check if an item was added to a set, without 2x (hash, lookup)(Python:如何检查一个项目是否被添加到一个集合中,没有 2x(散列,查找))
问题描述
我想知道是否有一种清晰/简洁的方法可以将某些内容添加到集合中,并检查它是否是在没有 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.
这篇关于Python:如何检查一个项目是否被添加到一个集合中,没有 2x(散列,查找)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python:如何检查一个项目是否被添加到一个集合中,没有 2x(散列,查找)


- 我如何卸载 PyTorch? 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01