【问题标题】:python: make a variable equal an operator (+,/,*,-)python:使变量等于运算符(+,/,*,-)
【发布时间】:2011-12-10 14:01:32
【问题描述】:

是否可以为变量分配数学运算符。

这是我目前得到的,只是一个示例(现在输入,所以不要担心简单的错误)

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

【问题讨论】:

    标签: python coding-style


    【解决方案1】:
    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)
    

    【讨论】:

    • +1 用于直接回答 OP 的问题并启发我了解一个有用的功能。
    【解决方案2】:

    另一个选择而不是那个长度,只要你只做正 50 或负 50 是:

    red_channel = red_channel + (flag * 50)
    

    变量“flag”是 1 或 -1;从而给你50或-50。这不会为这个小例子节省很多代码,但我有时会在方便的时候使用它。

    【讨论】:

    • 我建议不要使用flag,因为通常标志是布尔值。
    【解决方案3】:

    我喜欢内联表达式,所以:

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

    【讨论】:

      猜你喜欢
      • 2012-09-03
      • 1970-01-01
      • 2012-06-19
      • 2019-03-23
      • 2012-11-28
      • 2019-02-11
      • 1970-01-01
      • 2019-12-07
      • 1970-01-01
      相关资源
      最近更新 更多