Python在O(1)中的字典中获得随机密钥 [英] Python get random key in a dictionary in O(1)

查看:340
本文介绍了Python在O(1)中的字典中获得随机密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个支持FAST插入和删除(键,值)对的数据结构,以及获取随机密钥,这与字典中的random.choice(dict.keys())相同。 。我在互联网上进行了搜索,大多数人似乎对random.choice(dict.keys())方法感到满意,尽管它是线性时间。



我知道实现这个更快的是:




  • 我可以使用调整大小的哈希表。如果我保持键到插槽的比例在1和2之间,那么我可以选择随机索引,直到我打到非空插槽。我只看1到2个键,期望。

  • 我可以使用AVL树在保证最坏的情况下(日志n)获得这些操作,并以等级增加。



有没有什么简单的方法可以在Python中获得这个?这似乎应该是!

解决方案

这可能与上面列出的具体用例无关,但这是问题我找到一个方法来很好地获得一个字典中的任何键。



如果你不需要一个真正的随机选择,但只需要一些任意键,这里有两个简单的选项我发现:

  key = next(iter(d))#可能有点贵,但可能是O(1)

第二个只有在你快乐时才真正有用从字典消费键+值,并且由于突变将不会像算法有效:

 键,value = d.popitem()#可能不是O(1)特别是如果下一步
如果MUST_LEAVE_VALUE:
d [key] = value


I need a data structure that supports FAST insertion and deletion of (key, value) pairs, as well as "get random key", which does the same thing as random.choice(dict.keys()) for a dictionary. I've searched on the internet, and most people seem to be satisfied with the random.choice(dict.keys()) approach, despite it being linear time.

I'm aware that implementing this faster is possible:

  • I could use a resizing hash table. If I maintain that the ratio of keys to slots is between 1 and 2, then I can just choose random indices until I hit a non-empty slot. I only look at 1 to 2 keys, in expectation.
  • I can get these operations in guaranteed worst case O(log n) using an AVL tree, augmenting with rank.

Is there any easy way to get this in Python, though? It seems like there should be!

解决方案

This may not specifically relevant to the specific use case listed above, but this is the question I get when searching for a way to nicely get a hold of "any" key in a dictionary.

If you don't need a truly random choice, but just need some arbitrary key, here are two simple options I've found:

key = next(iter(d))    # may be a little expensive, but presumably O(1)

The second is really useful only if you're happy to consume the key+value from the dictionary, and due to the mutation(s) will not be as algorithmically efficient:

key, value = d.popitem()     # may not be O(1) especially if next step
if MUST_LEAVE_VALUE:
    d[key] = value

这篇关于Python在O(1)中的字典中获得随机密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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