采取行动的百分比机会

met*_*hyl 20 python

简单问题:percentage_chance = 0.36

if <don't know what>:
   #action here has 36% chance to execute
   pass
Run Code Online (Sandbox Code Playgroud)

我怎么解决这个问题?

Sil*_*ost 33

你可以使用random.random:

>>> import random
>>> if random.random() < percentage_chance:
    print('aaa')
Run Code Online (Sandbox Code Playgroud)


Blu*_*ers 11

import random
if random.randint(0,100) < 36:
    do_stuff()
Run Code Online (Sandbox Code Playgroud)

  • 最好使用`randrange`函数。 (3认同)

Ram*_*lat 7

只是为了使其更明确、更具可读性:

def probably(chance):
    return random.random() < chance

if probably(35 / 100):
    do_the_thing()
Run Code Online (Sandbox Code Playgroud)