1. 程式人生 > >python 以概率生成值

python 以概率生成值

import random
#以序列seq中值出現的概率來隨機生成某個值
def rand_pick(seq , probabilities):
    x = random.uniform(0 ,1)
    cumprob = 0.0
    for item , item_pro in zip(seq , probabilities):
        cumprob += item_pro
        if x < cumprob:
            break
    return item
value_list = [0 , 1]
probabilities = [0.4 , 0.6]
print(rand_pick(value_list, probabilities))

zip([iterable, ...])
zip()是Python的一個內建函式,它接受一系列可迭代的物件作為引數,將物件中對應的元素打包成一個個tuple(元組),然後返回由這些tuples組成的list(列表)。若傳入引數的長度不等,則返回list的長度和引數中長度最短的物件相同。利用*號操作符,可以將list unzip(解壓)

a = [0 , 1]

b = [0.4 , 0.6]

zipped = zip(a , b) 

輸出  [(0 , 0.4),(1 , 0.6)]

unzip = zip(*zipped)

輸出 [(0 , 1),(0.4 , 0.6)]