有没有更好的方法在python中编写多个elif语句?

我有一个带有 18 个if/elif语句的代码片段。is_over是检测鼠标所在位置的函数。pos表示鼠标的位置,每个按钮都是 x、y、宽度、高度值的列表。这是我的代码片段:

if is_over(pos, BUTTON_DIVIDE):
    print("/")
elif is_over(pos, BUTTON_MEMORY):
    print("mem")
elif is_over(pos, BUTTON_CLEAR):
    print("clear")
elif is_over(pos, BUTTON1):
    print("1")
elif is_over(pos, BUTTON2):
    print("2")
elif is_over(pos, BUTTON3):
    print("3")

虽然这看起来相当可读,但我想知道是否有更好的方法。我想我可以使用字典更好地压缩这段代码,但我不确定如何。

回答

使用元组列表和循环:

buttons = [
    (BUTTON_DIVIDE, "/") , (BUTTON_MEMORY, "mem"), (BUTTON_CLEAR, "clear"),
    (BUTTON1, "1"), (BUTTON2, "2"), (BUTTON3, "3")]

for button, text in buttons:
    if is_over(pos, button):
        print(text)
        break

甚至可以存储和调用函数:

def divide():
    print("/")

def mem():
    print("mem")

def clear():
    print("clear")

buttons = [(BUTTON_DIVIDE, divide), (BUTTON_MEMORY, mem), (BUTTON_CLEAR, clear)] 

for button, action in buttons:
    if is_over(pos, button):
        action()
        break


以上是有没有更好的方法在python中编写多个elif语句?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>