简体   繁体   English

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

[英]Changing the order of called functions randomly

I have a function whose outline is given below.我有一个 function,其概要如下。 In main() , I want to return the returned values of one of the functions but I want to choose it randomly.main()中,我想返回其中一个函数的返回值,但我想随机选择它。 As of now, it checks func1 first and proceeds only if func1 is some_val .截至目前,它首先检查func1并仅在func1 is some_val I want to be able to check func2 first sometimes as well.我有时也希望能够先检查func2

I realize that I could call both functions, create a list with the outcomes, and randomly shuffle the list but both func1 and func2 are quite a bit involved, so performance is an issue.我意识到我可以调用这两个函数,创建一个包含结果的列表,然后随机打乱列表,但是func1func2都涉及很多,所以性能是一个问题。

Is there a clean way to do it?有干净的方法吗?

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

Shuffle the list of functions, then iterate over that list, calling them one at a time.打乱函数列表,然后遍历该列表,一次调用一个。

def main():
    functions = [func1, func2, func3]
    random.shuffle(functions)

    for f in functions:
        if (rv := f()) is not some_val:
            return rv

Note that this does require each function to have the same signature (and take the same arguments), but it is trivial to create a list of zero-argument functions that call the "real" functions with the appropriate arguments. Eg,请注意,这确实需要每个 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()

Assuming func1() returns "hello" and func2() returns "world" ...假设func1()返回"hello"并且func2()返回"world" ...

>>> main()
["hello", "world"]
>>> main()
["world", "hello"]
>>> main()
["world", "hello"]

Pretty simple.很简单。 That's all you need to do.这就是您需要做的全部。 Functions can be stored as variables like this:函数可以像这样存储为变量:

>>> 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]()


Result:结果:

2
2
1
2
1
3
2
3
3
2

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

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