Is there a way to compare a value against multiple possibilities without repetitive if statements?

huangapple go评论72阅读模式
英文:

Is there a way to compare a value against multiple possibilities without repetitive if statements?

问题

我有一个具有多种可能输入的函数,每种输入都会触发不同的函数。

这里的示例代码有效,但它很不好,我不想使用这种代码:

def start(press_type):
    if press_type == "keyboard":
        function1()

    if press_type == "left click":
        function2()

    if press_type == "right click":
        function3()

    if press_type == "middle click":
        function4()

是否有一种方法可以编写该函数,而不重复使用这些 if/else 语句?

我尝试使用字典,但结果很难处理,而且我还有其他具有多个设置选项的参数,所以这种方法最终会变得复杂。

英文:

I have a function with an input that can be of multiple possibilities, and each one triggers a different function.

The example code here works, but it's very bad and I don't want to use this sort of code:

def start(press_type):
    if press_type == "keyboard":
        function1()

    if press_type == "left click":
        function2()

    if press_type == "right click":
        function3()

    if press_type == "middle click":
        function4()

Is there any way to write the function without repeating those if/else statements?

I tried to use a dictionary, but the result was difficult to work with, also, I have a couple other parameters with multiple set options, so this method would end up being convoluted eventually.

答案1

得分: 2

你可以使用模式匹配语句:

def start(press_type):
    match press_type:
        case "keyboard":
            function1()
        case "left clock":
            function2()
        # ...
英文:

You can use a pattern match statement:

def start(press_type):
    match press_type:
        case "keyboard":
            function1()
        case "left clock":
            function2()
        # ...

答案2

得分: 2

def start(press_type):
  match press_type:
    case 'keyboard':
      function1()
    case 'left click':
      function2()
    case 'right click':
      function3()
    case 'middle click':
      function4()
    case _:
      # 默认情况
    # ...等等。

参考链接: 结构模式匹配

英文:

Python 3.10+

def start(press_type):
  match press_type:
    case 'keyboard':
      function1()
    case 'left click':
        function2()
    case 'right click':
        function3()
    case 'middle click':
        function4()
    case _:
      # Default
    # ...and so on.

Reference: Structural Pattern Matching

答案3

得分: 2

我怀疑这个答案可能不太受欢迎,但迄今为止提供的match/case解决方案仅仅利用了Python 3.10中的一个新功能,这在很大程度上并没有真正简化你所暗示的多种选项,可能将来会被使用。

使用传统的字典方法然后为函数添加关键字选项也有其道理。

我认为这种方法不会比match/case方法更简单。(我可能错了!)

一个简单的例子:

def start(press_type, **kwargs):
    func = functions[press_type]
    func(**kwargs)

def function1(**kwargs):
    print("function 1 executed")

def function2(**kwargs):
    print("function 2 executed")
    if kwargs:
        if "key1" in kwargs:
            function21(kwargs["key1"])
        if "key2" in kwargs:
            function21(kwargs["key2"])
        if "key3" in kwargs:
            function23(kwargs["key3"])
        return
    print("    function 2 missing a parameter")

def function3(**kwargs):
    print("function 3 executed")

def function4(**kwargs):
    print("function 4 executed")

def function21(key=None):
    print("    function 21", key)

def function23(key=None):
    print("    function 23", key)

functions = {"keyboard": function1, "left click": function2, "right click": function3, "middle click": function4}

start("left click", key1=1, key2=2, key3=3)
start("keyboard")
start("left click", key1=42, key3="A")
start("right click")
start("left click")

输出:

function 2 executed
    function 21 1
    function 21 2
    function 23 3
function 1 executed
function 2 executed
    function 21 42
    function 23 A
function 3 executed
function 2 executed
    function 2 missing a parameter
英文:

I suspect that this answer will be unpopular but the match/case solutions, so far offered, simply make use of a new feature in python 3.10, which to a large degree doesn't really simplify the multiple options that you imply, may be used in the future.

There is a case for using a traditional dictionary approach and then adding a keywords option to the functions.

I don't see this approach being any less convoluted than the match/case approach. ( I may be wrong! )

A simple example:

def start(press_type, **kwargs):
    func = functions[press_type]
    func(**kwargs)

def function1(**kwargs):
    print("function 1 executed")

def function2(**kwargs):
    print("function 2 executed")
    if kwargs:
        if "key1" in kwargs:
            function21(kwargs["key1"])
        if "key2" in kwargs:
            function21(kwargs["key2"])
        if "key3" in kwargs:
            function23(kwargs["key3"])
        return
    print("    function 2 missing a parameter")

def function3(**kwargs):
    print("function 3 executed")

def function4(**kwargs):
    print("function 4 executed")

def function21(key=None):
    print("    function 21", key)

def function23(key=None):
    print("    function 23", key)


functions = {"keyboard":function1,"left click":function2,"right click":function3,"middle click":function4}


start("left click", key1=1, key2=2, key3=3)
start("keyboard")
start("left click", key1=42, key3="A")
start("right click")
start("left click")

Output:

function 2 executed
    function 21 1
    function 21 2
    function 23 3
function 1 executed
function 2 executed
    function 21 42
    function 23 A
function 3 executed
function 2 executed
    function 2 missing a parameter

huangapple
  • 本文由 发表于 2023年3月12日 17:45:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75712275.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定