从功能列表中获得一个随机函数和调用所选择的功能

问题描述 投票:1回答:1

我试图创建一个我可以调用一个函数,它从选择的功能列表中随机函数,并调用所选择的功能转化为行动。是否可能?在这里我都试过了。这会导致什么情况发生。

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()
python list function random
1个回答
3
投票

你的逻辑是罚款。你只需要打电话给你的ran_choice选择功能:

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

虽然,它可能更容易为已读:

def ran_choice():
    chosen_fn = random.choice(list_functions)
    chosen_fn()
© www.soinside.com 2019 - 2024. All rights reserved.