简体   繁体   English

根据权重,从python中的列表列表中随机选择列表

[英]Randomly select list from list of lists in python depending on weights

I have a list of lists, where each list is associated with a score/weight. 我有一个列表列表,其中每个列表与分数/重量相关联。 I want to produce a new list of lists by randomly selecting from the first one so that those with higher scores will appear more often. 我想通过从第一个列表中随机选择来生成一个新的列表列表,以便那些得分较高的列表更频繁地出现。 The line below works fine when population is just a normal list. population只是一个正常的列表时,下面的行可以正常工作。 But I want to have it for a list of lists. 但我希望将它列为清单列表。

population = [['a','b'],['b','a'],['c','b']]
list_of_prob = [0.2, 0.2, 0.6]

population = np.random.choice(population, 10, replace=True, p=list_of_prob)

This will give the output ValueError: a must be 1-dimensional 这将给出输出ValueError: a must be 1-dimensional

Instead of passing the actual list, pass a list with indexes into the list. 而不是传递实际列表,将带有索引的列表传递到列表中。

np.random.choice already allows this, if you pass an int n then it works as if you passed np.arange(n) . np.random.choice已经允许这个,如果你传递一个int n然后它就像你传递了np.arange(n)

So 所以

choice_indices = np.random.choice(len(population), 10, replace=True, p=list_of_prob)
choices = [population[i] for i in choice_indices]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM