python - 从函数列表中获取随机函数并调用所选函数
问题描述
我正在尝试创建一个可以调用的函数,它从函数列表中选择一个随机函数并将所选函数调用为行动。这甚至可能吗?这是我尝试过的。结果什么也没发生。
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()
推荐阅读
- django - Django alter admin save 更改另一个表字段
- java - 启动画面图片小android
- java - 在 Mac 上安装 JavaFX 15
- javascript - 将自定义错误类传递给 Express 错误中间件时,Node.Js 套接字挂起
- bash - 是否可以在 Mac 终端上使用 ls 命令在目录中按类型查看排序文件?
- html - 如何使用 CSS 删除文本开头的空格?
- r - 通过闪亮但在外部的渲染图传递图像对象
- c# - 传播 C# 鼠标离开事件
- asp.net-core - 用于点对点视频聊天的 ASP.NET Core 和 WebRTC
- flutter - Flutter:是否可以访问 BuildContext 的父状态?