【问题标题】:How can I perform the same statement if it passes one or more if statements?如果它通过一个或多个 if 语句,我如何执行相同的语句?
【发布时间】:2021-07-13 22:32:29
【问题描述】:

如果它通过一系列 if-elif 语句,我想执行相同的任务。

下面是我想要实现的一个示例。该程序运行时没有错误,但我想知道是否有更简单的方法可以将continue_program 分配给Yes,如果满足其中一个条件,则无需多次输入。

word_form = "A string!"
continue_program = "No"

number = 2

if number == 1:
    word_form = "one"
    continue_program = "Yes"
elif number == 2:
    word_form = "two"
    continue_program = "Yes"
elif number == 3:
    word_form = "three"
    continue_program = "Yes"

【问题讨论】:

  • 你可以说continue_program = number in (1,2,3),但我不相信它比你现在拥有的更好。
  • 你考虑过反转逻辑吗?不要去想告诉你什么时候continue_program应该是True的规则,想想那个告诉你什么时候应该是False的规则。然后您应该能够看到一种将其附加到其余代码的简单方法。
  • 如果我这样做,我会把那些 word_form 的东西放在字典里,然后做 if number in word_forms: / word_form = word_forms[number] / continue_program = True
  • 为了阐明我想要实现的目标,我稍微编辑了代码。我使用布尔值作为虚拟示例,但我将数据类型更改为字符串以澄清我为什么感到困惑。
  • 我会在 if 语句之前将标志设置为 True,如果它到达 else 子句,这意味着它永远不会匹配。

标签: python simplify


【解决方案1】:

这可能有点简洁了:

d = {1: "one", 2: "two", 3: "three"}

continue_program = bool(word_form := d.get(number, "")))

d 中查找number,这将产生所需的字符串或空字符串。作为副作用,将该字符串分配给word_form。该字符串的布尔值进一步分配给continue_program

一些例子;首先,number == 6

>>> bool(word_form := d.get(6, ""))
False
>>> word_form
''

现在,number == 1

>>> bool(word_form := d.get(1, ""))
True
>>> word_form
'one'

更新:使用条件表达式将True/False 映射到"Yes"/"No""

continue_program = "Yes" if (word_form := d.get(number, "")) else "No"

3.8 之前,

word_form = d.get(number, "")
continue_program = "Yes" if word_form else "No"

【讨论】:

  • 唯一需要注意的是,如果你像我一样被 3.8 之前的 Python 卡住,海象运算符 := 不可用。
【解决方案2】:

您可以保留您的 if 块并在最后检查“word_form”是否有长度,然后您可以将 coninue_program 分配给 True,例如:

word_form = ""
continue_program = False

number = 2

if number == 1:
    word_form = "one"
elif number == 2:
    word_form = "two"
elif number == 3:
    word_form = "three"

if len(word_form) > 0:
   continue_program = True

【讨论】:

    【解决方案3】:

    在这里,我可以想到两个使用类似 switch-case 的方法的解决方案:

    1)

    def num(arg):
    switcher = {
        1:True,
        2:True,
        3:True,
        4:False
    }
    return switcher.get(arg, False)
    
    def func1():
        print("hi func1")
    def func2():
        print("hi func2")
    def default():
        print("hi default")
    def num2(arg):
        switcher = {
            1:func1,
            2:func2,
        }
        return switcher.get(arg, default)
    
    num2(1)()
    print("space")
    num2(3)()
    

    会这样打印:

    hi func1
    space
    hi default
    

    您可以从这里switch-case了解更多信息

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-26
      • 1970-01-01
      • 1970-01-01
      • 2022-11-17
      • 1970-01-01
      • 2020-10-25
      相关资源
      最近更新 更多