带有可变数学运算符的Python if语句 [英] Python if-statement with variable mathematical operator

查看:97
本文介绍了带有可变数学运算符的Python if语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在if语句中插入一个变量数学运算符,这是我试图解析用户提供的数学表达式的一个示例:

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"

显然,以上操作失败,并显示SyntaxError: invalid syntax.我已经尝试过使用exec和eval了,但是在if语句中都无法使用,我必须采取哪些解决方案?

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?

推荐答案

将operator包与字典一起使用,以根据它们的等效文本查找操作符.所有这些都必须是一元运算符或二进制运算符,才能一致地工作.

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"

这篇关于带有可变数学运算符的Python if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆