Python if-statement with variable mathematical operator

后端 未结 3 2028
南旧
南旧 2020-12-18 20:47

I\'m trying to insert a variable mathematical operator into a if statement, an example of what I\'m trying to achieve in parsing user-supplied mathematical expressions:

3条回答
  •  情话喂你
    2020-12-18 21:08

    Use the operator package together with a dictionary to look up the operators according to their text equivalents. All of these must be either unary or binary operators to work consistently.

    import operator
    ops = {'==' : operator.eq,
           '!=' : operator.ne,
           '<=' : operator.le,
           '>=' : operator.ge,
           '>'  : operator.gt,
           '<'  : operator.lt}
    
    maths_operator = "=="
    
    if ops[maths_operator]("test", "test"):
        print "match found"
    
    maths_operator = "!="
    
    if ops[maths_operator]("test", "test"):
        print "match found"
    else:
        print "match not found"
    

提交回复
热议问题