python: make a variable equal an operator (+,/,*,-)

≯℡__Kan透↙ 提交于 2020-01-01 19:39:28

问题


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

回答1:


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)



回答2:


I like inline expressions, so:

red_channel += 50 if image == 'lighten' else -50



回答3:


Another option rather than going to that length, as long as you are only doing either positive 50 or negative 50 is:

red_channel = red_channel + (flag * 50)

The variable "flag" is either 1 or -1; thus giving you 50 or -50. This won't save a lot of code for this small example, but I use it at times when it is convenient.



来源:https://stackoverflow.com/questions/7815938/python-make-a-variable-equal-an-operator

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