Skip to main content
 首页 » 编程设计

python之如何以随机顺序运行函数

2025年05月04日14dflying

我想以随机顺序运行函数。它看起来像随机播放变量列表的“随机播放”函数。

输入:

def a(): 
    print('a') 
 
def b(): 
    print('b') 
 
def c(): 
    print('c') 
 
shuffle([a,b,c]) 

这是我想要的输出:

a 
b 
c 

或

a 
c 
b 

或

c 
b 
a 

或等等 如何以随机顺序运行函数?

请您参考如下方法:

random.shuffle是就地操作。所以你需要单独保留列表并对其进行洗牌。

import random 
 
functions = [a, b, c] 
random.shuffle(functions) 

现在,函数被打乱了,你只需要执行它们

for func in functions: 
    func() 

你可以把它存储在一个函数中,然后像这样做

def run_functions_in_random_order(*funcs): 
    functions = list(funcs) 
    random.shuffle(functions) 
    for func in functions: 
        func() 
 
run_functions_in_random_order(a, b, c) 

或者你可以像这样简单地使用闭包中的函数

def run_functions_in_random_order(*funcs): 
    def run(): 
        functions = list(funcs) 
        random.shuffle(functions) 
        for func in functions: 
            func() 
    return run 
 
random_exec = run_functions_in_random_order(a, b, c) 
 
random_exec() 
random_exec() 
random_exec()