【问题标题】:Python: How can I assign string representations of operators to mathematical operators using a dictionary?Python:如何使用字典将运算符的字符串表示形式分配给数学运算符?
【发布时间】:2021-01-08 19:06:20
【问题描述】:

我的目标是创建一个执行简单算术的 UDF。我希望该函数采用 2 个值,然后是运算符的字符串表示形式,例如“乘数”并在 x 到 y 上执行运算符。这是我第一次尝试,请原谅混乱。

def_myArithmetic(x, y, op):
     op={'multiply': *, 'divide': /, 'add': +, 'subtract':-}
     **some loop**
         **return calculation**

到目前为止我所管理的

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)

使用这组代码在调用函数时会返回错误。

我知道这本词典不起作用。我相信这与在一个参考中拥有多个键有关吗?

我相信我在正确的行附近的某个地方,但显然不知道如何写这个。当我尝试实施我选择的规则时,有一些东西可以参考会很有帮助。

感谢您的反馈

【问题讨论】:

  • 使用operator 模块。 operator.addoperator.mul
  • 我可以要求一个 UDF 中的示例吗?
  • {'multiply': operator.mul, ...}
  • 你的字典是正确的方法,你只需要使用那些函数作为值。
  • 这很有帮助,谢谢 Barmar

标签: python dictionary user-defined-functions


【解决方案1】:

您的字典变量正在替换 op 参数。为此使用不同的名称。

您需要使用字符串参数作为键来访问相应的字典元素。

你需要调用操作符函数,而不仅仅是把它和参数放在一个元组中。

for 循环没有任何理由。

没有operator.multiply,是operator.mul。查找完整列表 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)

【讨论】:

  • 这非常有用,非常感谢 Barmar!。我才 4 天前才开始编码。这已经将大量阅读付诸实践。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多