【问题标题】:Getting a random function from a list of functions and calling the selected function从函数列表中获取随机函数并调用所选函数
【发布时间】:2019-07-01 02:05:19
【问题描述】:

我正在尝试创建一个可以调用的函数,它会从函数列表中选择一个随机函数,然后将所选函数调用到操作中。这甚至可能吗?这是我尝试过的。结果什么也没发生。

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】:

    你的逻辑很好。只需调用ran_choice中选择的函数即可:

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

    虽然,它可能更容易理解为:

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

    【讨论】:

      猜你喜欢
      • 2021-12-15
      • 2012-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-02
      • 1970-01-01
      • 2015-03-02
      相关资源
      最近更新 更多