加权选择简短而简单 [英] Weighted choice short and simple

查看:44
本文介绍了加权选择简短而简单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果列表中有项目集合.我想根据另一个权重列表从该列表中进行选择.

If I have a collection of items in a list. I want to choose from that list according to another list of weights.

例如,我的收藏是['one', 'two', 'three'],权重是[0.2, 0.3, 0.5],我希望该方法在大约一半的抽签中给我三分".

For example my collection is ['one', 'two', 'three'] and the weights are [0.2, 0.3, 0.5], the I would expect the method to give me 'three' in about half of all draws.

最简单的方法是什么?

推荐答案

由于版本1.7,则可以使用 numpy.random.choice() :

Since numpy version 1.7 you can use numpy.random.choice():

elements = ['one', 'two', 'three'] 
weights = [0.2, 0.3, 0.5]

from numpy.random import choice
print(choice(elements, p=weights))

这篇关于加权选择简短而简单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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