python:使变量等于运算符(+,/,*, - ) [英] python: make a variable equal an operator (+,/,*,-)
本文介绍了python:使变量等于运算符(+,/,*, - )的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我现在得到的,只是一个示例(现在键入它,所以不要担心关于简单错误)
if image ==lighten:
red_channel = red_channel + 50
else :// image is darken
red_channel = red_channel - 50
注意我是如何重复完全相同的代码,用不同的运算符。
可以实现这样的:
if(image ==lighten):
operator = +
else:
operator = -
red_channel = red_channel operator 50
解决方案
import operator
if(image =='lighten'):
op = operator.add
else:
op = operator.sub
red_channel = op(red_channel,50)
或者,如果您有一些可能的操作,
op = {
'lighten':operator.add,
'darken':operator.sub,
...
}
red_channel = op [image](red_channel, 50)
is it possible to assign a variable a maths operator.
this is what I've currently got, just a sample (typed it in now, so dont worry about simple errors)
if image == "lighten":
red_channel = red_channel + 50
else: // image is darken
red_channel = red_channel - 50
notice how i am repeating the exact same code, with a different operator. Is it possible to achieve something like this:
if (image == "lighten"):
operator = +
else:
operator = -
red_channel = red_channel operator 50
解决方案
import operator
if (image == 'lighten'):
op = operator.add
else:
op = operator.sub
red_channel = op(red_channel, 50)
Or, if you have a number of possible operations,
op = {
'lighten':operator.add,
'darken':operator.sub,
...
}
red_channel = op[image](red_channel,50)
这篇关于python:使变量等于运算符(+,/,*, - )的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文