我有一个函数,它的概要如下所示。在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
发布于 2021-01-14 02:20:33
混洗函数列表,然后迭代该列表,一次调用一个函数。
def main():
functions = [func1, func2, func3]
random.shuffle(functions)
for f in functions:
if (rv := f()) is not some_val:
return rv
请注意,这确实要求每个函数具有相同的签名(并采用相同的参数),但是创建一个零参数函数列表来调用带有适当参数的“真实”函数是很容易的。例如,
functions = [lambda: func1(x, y), lambda: func2(z, "hi", 3.14)]
发布于 2021-01-14 02:22:51
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
发布于 2021-01-14 02:28: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
https://stackoverflow.com/questions/65707596
复制相似问题