A weighted version of random.choice

后端 未结 25 1863
闹比i
闹比i 2020-11-21 06:29

I needed to write a weighted version of random.choice (each element in the list has a different probability for being selected). This is what I came up with:



        
25条回答
  •  有刺的猬
    2020-11-21 06:49

    Since version 1.7.0, NumPy has a choice function that supports probability distributions.

    from numpy.random import choice
    draw = choice(list_of_candidates, number_of_items_to_pick,
                  p=probability_distribution)
    

    Note that probability_distribution is a sequence in the same order of list_of_candidates. You can also use the keyword replace=False to change the behavior so that drawn items are not replaced.

提交回复
热议问题