本文介绍了按照正态分布使用python从列表中选择一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想按照正态分布使用python从列表中选择一个元素.我有一个列表,例如

I would like to select one element from a list using python following the normal distribution. I have a list, e.g.,

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

例如,根据正态分布的概率密度函数(PDF),给定列表中的第3个元素应该被选择为最大概率.

For example, according to the probability density function (PDF) of normal distribution, the 3rd element in the given list should have the largest probability to be chosen.Any suggestions?

推荐答案

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

这篇关于按照正态分布使用python从列表中选择一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 04:25