[英]Python: How can I assign string representations of operators to mathematical operators using a dictionary?
My aim is to create a UDF that does simple arithmetic.我的目标是创建一个执行简单算术的 UDF。 I want the function to take 2 values, and then a string representation of an operator, for example 'mulitiply' and perform the operator on x to y.我希望 function 采用 2 个值,然后是运算符的字符串表示形式,例如“乘数”,并在 x 到 y 上执行运算符。 This is my first time attempting this, excuse the mess.这是我第一次尝试这个,请原谅混乱。
def_myArithmetic(x, y, op):
op={'multiply': *, 'divide': /, 'add': +, 'subtract':-}
**some loop**
**return calculation**
what I have managed so far到目前为止我所管理的
import operator
def do_arithmetic(x, y, op):
op={'multiply': operator.multiply,'divide': operator.divide,'add': operator.add ,'subtract': operator.subtract}
for i in range(x,y):
print (x, y)
using this bloc of code returns an error when calling the function.调用 function 时,使用这组代码会返回错误。
Im aware this dictionary does not work.我知道这本词典不起作用。 And i believe its to do with having multiple keys within one reference?我相信这与在一个参考中拥有多个键有关吗?
I believe im somewhere near the right lines but clearly have no idea how to write this.我相信我在正确的行附近的某个地方,但显然不知道如何写这个。 It would be very helpful to have something to reference when I try to implement the rules of my choosing.当我尝试实施我选择的规则时,有一些参考资料会很有帮助。
Thank you for your feedback感谢您的反馈意见
Your dictionary variable is replacing the op
parameter.您的字典变量正在替换op
参数。 Use a different name for this.为此使用不同的名称。
You need to use the string argument as a key to access the corresponding dictionary element.您需要使用字符串参数作为键来访问相应的字典元素。
You need to call the operator function, not just put it in a tuple with the arguments.您需要调用运算符 function,而不仅仅是将其与 arguments 放在一个元组中。
There's no reason for the for
loop. for
循环没有理由。
There's no operator.multiply
, it's operator.mul
.没有operator.multiply
,它是operator.mul
。 Find the full list here .在此处查找完整列表。
def do_arithmetic(x, y, op):
operations = {
'multiply': operator.mul,
'divide': operator.truediv,
'add': operator.add,
'subtract': operator.sub
}
return operations[op](x, y)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.