我有一个这样的功能列表:
def function1(a,b):
...
def function2(a,b,c,d):
...
def function3(a,b,c):
...
...and so on
并且这些函数被单独传递到这个函数中:
new_function = random_func(function2(a,b,c,d), other_parameter)
我想设置一个逻辑,我可以这样说:Call function2 30% of the time
。基本上,对于每个函数,我想声明一个概率值,表示它被传入的频率random_func()
。
更新
import random
def function1():
print('function1')
def function2():
print('function2')
def function3():
print('function3')
func_args = [(function1()),(function2()),(function3())]
# Choose random function
(func, args), = random.choices(func_args, weights=[0.5, 0.3, 0.2])
# probabilities ^^^^^^^^^^^^^^^
# Call it
result = func(*args)
print(result)
function1
function2
function3
Traceback (most recent call last):
File "/home/onur/Desktop/random_function.py", line 16, in <module>
(func, args), = random.choices(func_args, weights=[0.5, 0.3, 0.2])
TypeError: cannot unpack non-iterable NoneType object
您可以使用random.choices
来指定概率:
func_args = [
(function1, (a, b)),
(function2, (a, b, c, d)),
(function3, (a, b, c))
]
# Choose random function
(func, args), = random.choices(func_args, weights=[0.5, 0.3, 0.2])
# probabilities ^^^^^^^^^^^^^^^
# Call it
result = func(*args)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句