我有两个列表,每个列表的长度为100。第一个列表包含索引(称为列表i),第二个列表包含将选择每个索引的概率(称为列表P)。我想使用给定的概率选择一个索引。
我尝试使用以下代码:
index = random.choice(i, P)
从列表中选择一个索引。但是,我得到了错误:
ValueError:序列太大;不能大于32
是否有办法解决此错误,并从具有加权概率的较大(100个元素)列表中选择一个元素?也许我可以使用numpy.random()
以外的其他功能?或者也许是一次只查看列表中32个元素的方法(尽管我担心更改给定的概率分布)?预先感谢您的帮助!
random.choice()
仅采用一个参数:要选择的序列。
您需要random.choices()
函数,该函数将权重作为第二个(第一个命名的)参数。
示例用法:
import random
nums = [random.randint(0, 99) for _ in range(100)]
weights = [float(random.randint(0, 99)) for _ in range(100)]
weights = [w/sum(weights) for w in weights] # normalize to 1. not nessecary for random.choice
print(random.choices(nums, weights))