gpt4 book ai didi

python - 如何在非常大的python字典中获取随机值

转载 作者:太空狗 更新时间:2023-10-30 02:04:04 26 4
gpt4 key购买 nike

给定一个包含数百万个条目的 python 字典,从中获取和删除随机 (k,v) 对的最有效方法是什么?

字典不断增长,随机删除函数被调用得非常频繁。

python2 random_key = random.choice(the_dict.keys()) 引用最多的解决方案太慢了,因为首先创建了所有键的列表。由于字典中有很多元素,此解决方案不起作用。

另一个建议的解决方案是the_dict.popitem(),但这不会返回真正的随机对象,而是取决于dict 的内部排序。

第三种也是减慢速度的解决方案是迭代器:

 it = the_dict.iterkeys()

for i in range (random.randint(0, len(the_dict)-1)):
next(it)
random_key = next(it)

remove_random() 旁边,有时特定键需要 the_dict.pop(x)。因此,一个简单的基于列表的二级索引是行不通的。

这个问题可以用字典有效地解决吗?

最佳答案

一种解决方案是使用双向映射将每个键映射到一个整数,以允许通过使用 random.randrange(0,N) 从双向映射到键的整数范围中进行选择来随机选择一个键,其中N是键的数量。

添加一个新键只是简单地为它分配下一个更高的整数。删除键会将该键的 int 重新分配给在删除键值对之前分配给先前最高 int 的键。为清楚起见,提供了 Python 代码。

Python代码:

def create(D): # O(len(D))
# Create the bidirectional maps from the dictionary, D
keys = D.keys()
ints = range(len(keys)
int_to_key = dict(zip(keys, ints))
key_to_int = dict(zip(ints, keys))
return (int_to_key, key_to_int)

def add(D, int_to_key, key_to_int, key, value): # O(1)
# Add key-value pair (no extra work needed for simply changing the value)
new_int = len(D)
D[key] = value
int_to_key[new_int] = key
key_to_int[key] = new_int

def remove(D, int_to_key, key_to_int, key): # O(1)
# Update the bidirectional maps then remove the key-value pair

# Get the two ints and keys.
key_int = key_to_int[key]
swap_int = len(D) - 1 # Should be the highest int
swap_key = int_to_key[swap_int]

# Update the bidirectional maps so that key now has the highest int
key_to_int[key], key_to_int[swap_key] = swap_int, key_int
int_to_key[key_int], int_to_key[swap_int] = swap_key, key

# Remove elements from dictionaries
D.remove(key)
key_to_int.remove(key)
int_to_key.remove(key)

def random_key(D, int_to_key): # O(1)
# Select a random key from the dictionary using the int_to_key map
return int_to_key[random.randrange(0, len(D))]

def remove_random(D, int_to_key, key_to_int): # O(1)
# Randomly remove a key from the dictionary via the bidirectional maps
key = random_key(D, int_to_key)
remove(D, int_to_key, key_to_int, key)

注意:在不使用上述适当函数的情况下从 D 添加/删除键将破坏双向映射。这意味着最好将其实现为一个类。

关于python - 如何在非常大的python字典中获取随机值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24630804/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com