在 Python 中是否可以在 RETURN 语句之后制作一个包含多个 IF 和 OR 的单行代码?

Is it possible in Python to make a one-liner with multiple IF and OR after RETURN statement?

我希望我很清楚我想用这个函数做什么:

def this_one_operator(math_operator, num1, num2):
    return num1 * num2 if operator == "*" \
        or num1 / num2 if operator == "/" \
        or num1 + num2 if operator == "+" \
        or num1 - num2 if operator == "-"

显然,它不起作用(SyntaxError:语法无效)。

抱歉,如果我重复这个问题。我尽力在这里找到如何处理这个问题。另外,如果问题不准确,我很感激如何编辑问题的任何建议。

谢谢。

Python 有一个 value if condition else default ternary operation,,您可以将其叠加以获得此结果。然而,它不是很紧凑,做你似乎想做的事情也不是很 pythonic。

相反,您可以尝试:

import operator 

def binary_op(op, lopd, ropd):
    return { '/' : operator.floordiv,
             '*' : operator.mul,
             '+' : operator.add,
             '-' : operator.sub,
             '%' : operator.mod }[op](lopd, ropd)

是的,但是很丑。

return (x * y if operator == "*" else
        x / y if operator == "/" else
        x + y if operator == "+" else
        x - y if operator == "-" else
        None)

或者:

import operator
OPERATORS = {
    '*': operator.mul,
    '/': operator.truediv,
    '+': operator.add,
    '-': operator.sub,
}

return OPERATOR[op](x, y)

这不是很漂亮,但它有效:

def this_one_operator(math_operator, num1, num2):
    return (operator == "/")*(num1/num2) + \
           (operator == "+")*(num1+num2) + \
           (operator == "-")*(num1-num2) + \
           (operator == "*")*(num1*num2)

之所以可行,是因为布尔语句等于 0 或 1,因此将它们乘以正确的表达式并对正确的总数求和将产生正确的结果。

编辑:实际上,这并不像其他人指出的那样有效,因为除法运算可能会导致未定义的结果。