简体   繁体   English

python中是否有内置的“偏差”功能?

[英]Is there a built-in “deviation”-function in python?

I don't know the proper terminology for this, so please correct me if the term "deviation" is wrong for what I'm talking about, but I am wondering if there is a built-in function to deviate a value using standard mathematical operators in Python that works by passing it an original value, an operand and a modification value. 我不知道合适的术语,所以如果术语“偏差”与我所说的不符,请更正我,但我想知道是否有内置函数使用标准数学公式来使值偏离Python中的运算符,通过向其传递原始值,操作数和修改值来工作。

I would need this to specify a "deviation" at the top layer of a program which is later applied to a value that is dynamically retrieved. 我需要它在程序的顶层指定“偏差”,然后将其应用于动态检索的值。

What I currently have is a function like this: 我目前拥有的是这样的功能:

def deviateValue(value, deviation):
    value = float(value)
    operand = deviation[0]
    modifier = float(deviation[1:])
    if operand == "+":
        value += modifier
    elif operand == "-":
        value -= modifier
    elif operand == "*":
        value *= modifier
    elif operand == "/":
        value /= modifier
    elif operand == "=":
        value = modifier
    else:
        logger.warning("WARNING: Operand not implemented:", operand)
        return False

    return value

...which works, but it sort of feels like something basic like this should already implemented somewhere in the base package. ...可以,但是感觉像这样的基本东西应该已经在基本包中的某个地方实现了。

So to sum up the question: Does a function like this already exist somewhere within the basic Python modules? 因此,总结一下这个问题:基本的Python模块中是否已经存在这样的函数? At the very least, I could not find it in the math module. 至少,我在math模块中找不到它。

Instead of a + b you can also do operator.add(a, b) . 除了a + b您还可以执行operator.add(a, b) With that in mind you now only have to create a mapping from your operator strings to the according operator.* functions, and call the result: 考虑到这一点,您现在只需创建一个从您的运算符字符串到相应operator.*函数的映射,然后调用结果:

import operator

def deviate(first, operand, second):
    ops = {
        '+': operator.add,
        '-': operator.sub,
        '*': operator.mul,
        '/': operator.truediv,
        '//': operator.floordiv,
        '%': operator.mod,
    }

    return ops[operand](first, second)

# 2 + 3 = 5
deviate(2, '+', 3)
# 2 * 3 = 6
deviate(2, '*', 3)
# 10 % 3 = 1
deviate(10, '%', 3)

Why not simply evaluate a string that is generated from the three inputs like this: 为什么不简单地评估从以下三个输入生成的字符串:

original=2
operand='+'
modifier=3
eval(str(original)+operand+str(modifier))

I would not recommend this, but it will do the job: 建议这样做,但是可以做到:

def deviateValue(v,d):
    try:
        return eval(str(v)+d)
    except:
        logger.warning("WARNING: Could not evaluate %r %s" % (v,d))
        return False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM