Python在O(1)中的字典中获得随机密钥 [英] Python get random key in a dictionary in O(1)
问题描述
我知道实现这个更快的是:
- 我可以使用调整大小的哈希表。如果我保持键到插槽的比例在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屋!