下面是自己的简单实现,思路是随机从1-100取值n,若n小于等于指定的概率数则执行

import random

def random_run(probability, func, *args):
    """以probability%的概率执行func(*args)"""
    num = random.randint(1,100)
    if num <= probability:
        func(*args)

def print_sth(name):
    print(f'{name}你中奖了!')

if __name__ == '__main__':
    random_run(30, print_sth, 'jack')#以30%的概率执行print_sth('jack')
上一篇