我有一个函数,它的概要如下所示。在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: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
https://stackoverflow.com/questions/65707596
复制相似问题