Select 列表中的一个元素使用 python 服从正态分布

Select one element from a list using python following the normal distribution

我想 select 使用 python 遵循正态分布的列表中的一个元素。我有一个列表,例如

alist = ['an', 'am', 'apple', 'cool', 'why']

例如,根据正态分布的概率密度函数(PDF),给定列表中的第 3 个元素应该有最大的概率成为 chosen.Any 个建议?

from random import normalvariate

def normal_choice(lst, mean=None, stddev=None):
    if mean is None:
        # if mean is not specified, use center of list
        mean = (len(lst) - 1) / 2

    if stddev is None:
        # if stddev is not specified, let list be -3 .. +3 standard deviations
        stddev = len(lst) / 6

    while True:
        index = int(normalvariate(mean, stddev) + 0.5)
        if 0 <= index < len(lst):
            return lst[index]

然后

alist = ['an', 'am', 'apple', 'cool', 'why']
for _ in range(20):
    print(normal_choice(alist))

给予

why
an
cool
cool
cool
apple
cool
apple
am
am
apple
apple
apple
why
cool
cool
cool
am
am
apple

你确定你真的想要正态分布吗,你可以看看 Beta Distribution,它可能会满足你的需要,例如:

>>> import random
>>> from collections import Counter
>>> alist = ['an', 'am', 'apple', 'cool', 'why']
>>> Counter(alist[int(random.betavariate(2, 2)*len(alist))] for _ in range(100))
Counter({'am': 20, 'an': 9, 'apple': 34, 'cool': 23, 'why': 14})
>>> Counter(alist[int(random.betavariate(10, 10)*len(alist))] for _ in range(100))  
Counter({'am': 18, 'apple': 64, 'cool': 18})