我有一个函数,它的轮廓如下。在main()
中,我想返回其中一个函数的返回值,但我想随机选择它。到目前为止,它首先检查func1
,只有当func1 is some_val
时才继续检查。我希望有时也能先检查func2
。
我意识到我可以调用这两个函数,用结果创建一个列表,并随机洗牌列表,但func1
和func2
都涉及到相当多,所以性能是一个问题。
有干净的方法吗?
def func1():
... do things
return val
def func2():
... do things
return val
def main():
if func1() is not some_val:
return func1()
elif func2() is not some_val:
return func2()
else:
return None
打乱函数列表,然后遍历该列表,每次调用一个。
def main():
functions = [func1, func2, func3]
random.shuffle(functions)
for f in functions:
if (rv := f()) is not some_val:
return rv
请注意,这确实要求每个函数具有相同的签名(并接受相同的参数),但是创建一个零参数函数列表来调用"real"函数是微不足道的。带有适当参数的函数。例如,
functions = [lambda: func1(x, y), lambda: func2(z, "hi", 3.14)]
import random
def f1():
print(1)
def f2():
print(2)
def f3():
print(3)
listf=[f1,f2,f3]
for i in range(10):
random_index = random.randrange(0,len(listf))
listf[random_index]()
结果:2
2
1
2
1
3
2
3
3
2
from random import shuffle
def main(list_of_functions=[func1, func2], *args, **kwargs):
shuffle(list_of_functions)
outcomes = []
for func in list_of_functions:
outcomes.append(func(*args, **kwargs))
return outcomes
main()
假设func1()
返回"hello"
, func2()
返回"world"
…
>>> main()
["hello", "world"]
>>> main()
["world", "hello"]
>>> main()
["world", "hello"]
相当简单。这就是你所需要做的。函数可以像这样存储为变量:
>>> def otherFunc():
... print("hi")
...
>>> otherFunc()
hi
>>> someFunc = otherFunc
>>> someFunc()
hi