繁体   English   中英

随机改变被调用函数的顺序

[英]Changing the order of called functions randomly

我有一个 function,其概要如下。 main()中,我想返回其中一个函数的返回值,但我想随机选择它。 截至目前,它首先检查func1并仅在func1 is some_val 我有时也希望能够先检查func2

我意识到我可以调用这两个函数,创建一个包含结果的列表,然后随机打乱列表,但是func1func2都涉及很多,所以性能是一个问题。

有干净的方法吗?

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

请注意,这确实需要每个 function 具有相同的签名(并采用相同的参数),但是创建一个零参数函数列表是微不足道的,这些函数使用适当的 arguments 调用“真实”函数。例如,

functions = [lambda: func1(x, y), lambda: func2(z, "hi", 3.14)]
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
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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM