python if语句带有变量数学运算符 [英] python if statement with variable mathematical operator

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

问题描述

我正在尝试将一个变量数学运算符插入到if语句中,这是我想要实现的一个例子: -

Hi, I'm trying to insert a variable mathematical operator into a if statement, an example of what I'm trying to achieve:-

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"

显然,上述内容因语法错误而失败:语法无效。我已经尝试过使用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?

推荐答案

将运算符包与字典一起使用,以根据文本等效项查找运算符。所有这些必须是一元或二元运算符才能始终如一地工作。

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天全站免登陆