【问题标题】:Expressions in a dictionary mapping字典映射中的表达式
【发布时间】:2016-02-05 21:18:13
【问题描述】:

我有一系列的条件句:

if ':' in particle:
    do something
elif 'eq' in particle:  
    do something else
elif 'lt' in particle:
    do another thing
elif 'le' in particle:
    etc.
elif 'gt' in particle:
    etc., etc.
elif 'ge' in particle:
    etc., etc., etc.
elif 'ne' in particle:
    more etc.

我想使用字典映射模式来实现这一点,但是键有问题。

我试过了:

def case_evaluator(particle):
    switcher = {
        ':' in particle: do something,
        'eq' in particle: do something else,
        'lt' in particle: do another thing,
        ...
    }
    return switcher.get(particle, "nothing")

但是,我一直“什么都没有”。东西怎么可能一无所获?

这看起来应该很简单,但是唉......

【问题讨论】:

  • 不应该在某处声明“参数”吗?
  • 对不起...我刚刚编辑了这个。

标签: python dictionary switch-statement conditional mapper


【解决方案1】:

您可能想要一个将字符映射到函数的字典。

char_function_dict = {
    ':': colon_function,
    'eq': eq_function,
    'lt': lt_function
    # ...and so on...
}

然后,您可以遍历此字典中的键值对。

def apply_function(particle):
    for char, function in char_function_dict.items():
        if char in particle:
            function()

但是,请注意,此结构实际上并没有使用任何特定于字典的内容,也没有保留检查字符的顺序。使用 2 元素元组的列表可能会更简单。

char_functions = [
    (':', colon_function),
    ('eq', eq_function),
    ('lt', lt_function)
    # ...and so on...
]

def apply_function(particle):
    for char, function in char_functions:
        if char in particle:
            function()
            break # so successive functions are not run

设置这些结构中的任何一个以允许将参数和/或关键字参数传递给函数很容易:

def apply_function(particle, *args, **kwargs):
    for char, function in char_functions:
        if char in particle:
            function(*args, **kwargs)
            break

【讨论】:

  • 不错。我喜欢。我刚刚发现这个,或多或少等同于您的回复:stackoverflow.com/questions/29433635/…>...
【解决方案2】:

你在正确的轨道上。这称为函数分派。 它需要看起来更像这样:

def case_evaluator(particle):
    switcher = {
        ':': do_something,
        'eq': do_something_else,
        'lt': do_another_thing,
        ...
    }
    return switcher.get(particle, lambda: "nothing")()

其中 do_something 等都是不带参数的函数。 lambda x: "nothing" 是一个 lambda 函数,它总是返回“nothing”——如果在 switcher.keys() 中找不到 particle,它是默认调用的函数。

【讨论】:

  • 很抱歉对此投反对票。如果您对其进行编辑,我将再次对其进行投票。您的解决方案也有效。
猜你喜欢
  • 2020-03-15
  • 2021-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多