#### Select a string from list with a probability

``````import random

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

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
``````

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

``````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]
``````
1 如何从列表中选择随机字符串

3 在字符串列表中选择一个字符串

2016-01-09 06:45:08 2 2626   c#/ linq
5 从字符串列表中选择一个字符串

7 如何从列表中选择一个随机字符并加倍并以成对的字符串输出

8 如何从索引列表中选择嵌套列表中的字符串

2019-03-17 19:11:13 1 51   r

© 2020-2022 STACKOOM.COM