【问题标题】:How to use user input as comparison operator? [duplicate]如何使用用户输入作为比较运算符? [复制]
【发布时间】:2020-06-20 09:15:53
【问题描述】:

实现这一目标的最佳方法是什么:

user_input = ">"

if 2 user_input 3:
    print("yes")

我想避免写另一个if 声明:

if user_input == ">":
    if 2 > 3:
        print("yes")

【问题讨论】:

  • 使用and运营商!! if user_input == ">" and 2 > 3:

标签: python


【解决方案1】:

你可以使用operator模块:

from operator import gt, lt
op_dict = {">": gt, "<": lt}
user_input = input("Enter comparison operator: ")
comp = op_dict[user_input]
if comp(2, 3):
    print("Yes")

【讨论】:

    【解决方案2】:

    您可以将用户输入映射到不同的功能,然后您可以选择并应用到您的号码。

    例子:

    commands = {
      ">" : lambda x, y : x > y,
      "<" : lambda x, y : x < y,
      ">=": lambda x, y : x >= y
    }
    
    user_selection = input() # say ">" is chosen
    if commands[user_selection](2, 3):
        print("yes")
    

    【讨论】:

      【解决方案3】:

      您可以使用 eval 来评估任何表达式。

      根据您上面的代码。输出可以通过以下方式实现。

      user_input = ">"
      
      if eval("2"+user_input+"3"):
          print("yes")
      

      【讨论】:

      • 你可以使用eval,但你不应该使用eval。在 99.9% 的情况下,有更好的方法。阅读:Eval really is dangerous.
      【解决方案4】:

      你可以试试这个:

      if user_input == ">":
          print("yes\n"*(2 > 3), end='')
      

      【讨论】:

        【解决方案5】:

        如此简单,如果你想避免另一个 if 语句,只需使用 and 运算符

        user_input = ">"
        n1 = 2
        n2 = 3
        if user_input == ">" and n1 > n2:
                print("yes")
        

        【讨论】:

          【解决方案6】:

          您可以使用eval 函数将字符串评估为语句:

          user_input = ">"
          n1 = 2
          n2 = 3
          
          if eval(str(n1) + user_input + str(n2)):
             print("yes")
          

          【讨论】:

            猜你喜欢
            • 2020-03-14
            • 2013-01-23
            • 1970-01-01
            • 2012-10-05
            • 2023-03-26
            • 2019-04-21
            • 2018-03-19
            • 2012-10-19
            • 2012-03-08
            相关资源
            最近更新 更多