Skip to main content
 首页 » 编程设计

python之使用 python 遵循正态分布从列表中选择一个元素

2025年05月04日16lori

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

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

例如,根据正态分布的概率密度函数(PDF),给定列表中的第 3 个元素应该有最大的概率被选中。有什么建议吗?

请您参考如下方法:

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