簡體   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