Python if-statement with variable mathematical operator

二次信任 提交于 2019-11-28 02:40:07

问题


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:

maths_operator = "=="

if "test" maths_operator "test":
       print "match found"

maths_operator = "!="

if "test" maths_operator "test":
       print "match found"
else:
       print "match not found"

obviously the above fails with SyntaxError: invalid syntax. I've tried using exec and eval but neither work in an if statement, what options do I have to get around this?


回答1:


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"



回答2:


Use the operator module:

import operator
op = operator.eq

if op("test", "test"):
   print "match found"



回答3:


I've tried using exec and eval but neither work in an if statement

For the sake of completeness it should be mentioned that they do work, even if the posted answers provide a better solution. You'll have to eval() the whole comparison, not just the operator:

maths_operator = "=="

if eval('"test"' + maths_operator '"test"'):
       print "match found"

or exec the line:

exec 'if "test"' + maths_operator + '"test": print "match found"'


来源:https://stackoverflow.com/questions/11847359/python-if-statement-with-variable-mathematical-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!