【问题标题】:Select a string from list with a probability以概率从列表中选择一个字符串
【发布时间】:2021-01-25 19:23:15
【问题描述】:

我试图创建一个函数,它以给定的概率返回一个随机单词字符(字母)。我的参考是this 维基百科页面。在表格中,您可以看到字母 t 有 16% 的机会成为第一个字母。然而,字母 x 有 0.045% 的机会。我想包含每个字母。

我确信有比这样做更好的方法:

import random

def selectLetter():
    letters = ['t', 't', (x16000 times), 'o', (x7600 times),... , 'x', (x45 times)]
    random.choice(letters)

加分:如果代码能够接受一组/列表(或其他)字母并排除它们并相应地调整概率。这不是必需的,但它会很棒!

如何创建这样的函数?

【问题讨论】:

标签: python python-3.x list random


【解决方案1】:

此函数返回一个随机字母,根据维基百科页面上的前几个条目加权。您需要完成字母字典(使概率加起来为 1)才能使其完全发挥作用。

import random
def random_weighted_letter():
    letters = {"a": 0.017,"b": 0.044,"c": 0.052,"d": 0.032,"e": 0.028,"f": 0.04}
    return random.choices(population=list(letters.keys()), weights=letters.values())[0]

【讨论】:

    【解决方案2】:

    查看加权列表:

    from numpy.random import choice
    
    elements = [1, 2, 3] 
    weights = [0.2, 0.1, 0.7]
    
    one = 0
    two = 0
    three = 0
    for i in range(1000):
        num = choice(elements, p=weights)
        if num==1:
            one+=1
        elif num==2:
            two+=1
        else:
            three+=1
    
    print(one,two,three, one/1000, two/1000, three/1000)
    

    输出:

    217 108 675 0.217 0.108 0.675
    

    如果有更多循环,您最终可能会得到权重设置的确切概率。当然用你的字母和权重替换列表,概率在 0-1 范围内,总和必须为 1 (100%)

    您还可以将大小提供给选择,创建具有给定概率的所需大小的随机值列表:

    res = choice(elements, p=weights, size=1000)
    print(list(res).count(1)) #199 first time, next time 178
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-25
      • 1970-01-01
      • 2013-03-22
      • 2021-05-02
      • 2017-11-23
      • 1970-01-01
      • 1970-01-01
      • 2017-08-09
      相关资源
      最近更新 更多