Python:如何检查一个项目是否被添加到一个集合中,没有 2x(哈希,查找) [英] Python: how to check if an item was added to a set, without 2x (hash, lookup)

查看:48
本文介绍了Python:如何检查一个项目是否被添加到一个集合中,没有 2x(哈希,查找)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这是你可以做的,但它有 2 倍散列的项目

if item not in some_set: # <-- hash &抬头some_set.add(item) # <-- 散列 &查找,检查项目已经在集合中其他任务()

这适用于单个散列和查找,但有点难看.

some_set_len = len(some_set)some_set.add(item)如果 some_set_len != len(some_set):其他任务()

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

解决方案

我认为没有内置的方法可以做到这一点.当然,您可以编写自己的函数:

def do_add(s, x):l = 镜头s.add(x)返回 len(s) != ls = 设置()打印(do_add(s,1))打印(do_add(s,2))打印(do_add(s,1))打印(do_add(s,2))打印(do_add(s,4))

或者,如果您更喜欢神秘的单行文字:

def do_add(s, x):返回 len(s) != (s.add(x) 或 len(s))

(这依赖于从左到右的计算顺序以及 set.add() 总是返回 None 的事实,这是错误的.)

抛开这一切不谈,如果双重哈希/查找明显是性能瓶颈,并且如果使用函数明显更快,我才会考虑这样做.

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?

解决方案

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.

这篇关于Python:如何检查一个项目是否被添加到一个集合中,没有 2x(哈希,查找)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆