如何在python中创建概率条件流?

2024-10-03 13:17:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我考虑的是一个条件流,它大致在一半时间内产生一个浮点,或者在一半时间内产生一个整数。我的代码是:

import random
for i in range(10):
    binarychoice=random.randint(0,1)
    if binarychoice=0:
        pass #do whatever you need to do, return an integer
    elif binarychoice=1:
        pass #do whatever you need, return a float

是这样吗?然而,有没有库可以用来做这样一个概率条件流(因为我从来没有真正听说过,主要是因为缺乏经验),这样我就可以简单地写一些沿“X…或Y”行的东西,执行X或Y的概率是一半?你知道吗


Tags: 代码importyoureturn时间整数randompass
1条回答
网友
1楼 · 发布于 2024-10-03 13:17:02

如果只是50/50,这就更干净了:

import random
for i in range(10):
    if random.randint(0,1):
        pass #do whatever you need to do, return an integer
    else:
        pass #do whatever you need, return a float

或更灵活的概率:

import random
for i in range(10):
    if random.random() < .8:
        pass #do whatever you need to do, return an integer
    else:
        pass #do whatever you need, return a float

相关问题 更多 >