繁体   English   中英

从函数列表中获取随机函数并调用所选函数

[英]Getting a random function from a list of functions and calling the selected function

我正在尝试创建一个我可以调用的函数,它从函数列表中选择一个随机函数,并将所选函数调用为动作。 这甚至可能吗? 这是我尝试过的。 这导致什么都没发生。

import random

def ran1(): 
    print("test1")

def ran2(): 
    print("test2") 

def ran3(): 
    print("test3") 

def ran4(): 
    print("test4")

list_functions = [ran1,ran2,ran3,ran4]

def ran_choice():
    random.choice(list_functions)

ran_choice()

你的逻辑很好。 你只需要调用你在ran_choice选择的函数:

def ran_choice():
    random.choice(list_functions)()

虽然,它可能更容易阅读:

def ran_choice():
    chosen_fn = random.choice(list_functions)
    chosen_fn()

暂无
暂无

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

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