【问题标题】:Depending on arguments execute action根据参数执行动作
【发布时间】:2021-03-12 10:04:25
【问题描述】:

我正在尝试自动解决故障单。 事实上,我的想法是用以下格式解析输入:server_name | alert,并根据 server_namealert 是什么,执行一个动作(=函数)。 我的第一个想法是使用 if/elif 块代码来解决这个问题,但开始编写代码在我看来效率低下且冗长。

if server_name == 'Z':
    if alert == 'a':
        action1()
    elif alert == 'b':
        action2()
        ...
elif server_name == 'Y':
    if alert == 'a':
        action3()
    elif alert == 'b':
        action4()
        ...
...

我进行了研究,创建语法似乎是一个更好的解决方案,可能使用 re 模块、ast 模块或 dis 模块。但是我看到的语法总是包括数学,我只需要评估字符串。 有谁知道什么最适合这种情况,或者您知道是否有更好的解决方案?谢谢。

【问题讨论】:

  • 制作字典,而不是嵌套 if/elif/else 块
  • 类似:dict = {"server_name1": "alert1", "server_name2": "alert2"...} 并创建一个 if/elif 代码块来评估 key:value 以执行行动?

标签: python python-3.x regex string grammar


【解决方案1】:

像这样以元组作为键的东西:

actions = {('Z', 'a'):action1,
           ('Z', 'b'):action2,
           ('Y', 'a'):action3,
           ('Y', 'b'):action4}
server = 'Y'
alert = 'a'
actions[(server, alert)]() # execute it

您可以使用命名元组等。

嵌套字典

actions = {'Z':{'a':action1,
                'b':action2},
           'Y':{'a':action3,
                'b':action4}}
server = 'Y'
alert = 'a'
actions[server][alert]() # execute it

在这两种情况下,我都假设您也定义了用于操作的函数。

注意,在 3.10(现在处于开发阶段)中,我们将获得 structural pattern matching

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多