将字符串转换为运算符

问题描述 投票:0回答:9

如何将

"+"
之类的字符串转换为运算符加号?

python evaluation
9个回答
149
投票

使用查找表:

import operator
ops = { "+": operator.add, "-": operator.sub } # etc.

print(ops["+"](1,1)) # prints 2 

41
投票
import operator

ops = {
    '+' : operator.add,
    '-' : operator.sub,
    '*' : operator.mul,
    '/' : operator.truediv,  # use operator.div for Python 2
    '%' : operator.mod,
    '^' : operator.xor,
}

def eval_binary_expr(op1, oper, op2):
    op1, op2 = int(op1), int(op2)
    return ops[oper](op1, op2)

print(eval_binary_expr(*("1 + 3".split())))
print(eval_binary_expr(*("1 * 3".split())))
print(eval_binary_expr(*("1 % 3".split())))
print(eval_binary_expr(*("1 ^ 3".split())))

16
投票

如何使用查找字典,但使用 lambdas 而不是运算符库。

op = {'+': lambda x, y: x + y,
      '-': lambda x, y: x - y}

然后你可以这样做:

print(op['+'](1,2))

它会输出:

3

11
投票

您可以尝试使用 eval(),但如果字符串不是您提供的,那将很危险。 否则你可能会考虑创建一个字典:

ops = {"+": (lambda x,y: x+y), "-": (lambda x,y: x-y)}

etc...然后调用

ops['+'] (1,2)
或者,对于用户输入:

if ops.haskey(userop):
    val = ops[userop](userx,usery)
else:
    pass #something about wrong operator

6
投票

每个算子都有对应的魔法方法

OPERATORS = {'+': 'add', '-': 'sub', '*': 'mul', '/': 'div'}

def apply_operator(a, op, b):

    method = '__%s__' % OPERATORS[op]
    return getattr(b, method)(a)

apply_operator(1, '+', 2)

2
投票

如果安全(不在服务器等上),请使用

eval()

num_1 = 5

num_2 = 10

op = ['+', '-', '*']

result = eval(f'{num_1} {op[0]} {num_2}')

print(result)

输出: 15


1
投票

我知道你想做这样的事情: 5"+"7 所有 3 件事都将通过变量传递, 所以 例子:

import operator

#define operators you wanna use
allowed_operators={
    "+": operator.add,
    "-": operator.sub,
    "*": operator.mul,
    "/": operator.truediv}

#sample variables
a=5
b=7
string_operator="+"

#sample calculation => a+b
result=allowed_operators[string_operator](a,b)
print(result)

0
投票

我遇到了同样的问题,使用 Jupyter Notebook,我无法导入 operator 模块。所以上面的代码帮助了我洞察力,但无法在平台上运行。我想出了一个有点原始的方法来使用所有的基本功能,这里是:(这可能会被大量改进,但这是一个开始......)

# Define Calculator and fill with input variables
# This example "will not" run if aplha character is use for num1/num2 
def calculate_me():
    num1 = input("1st number: ")
    oper = input("* OR / OR + OR - : ")
    num2 = input("2nd number: ")

    add2 = int(num1) + int(num2)
    mult2 = int(num1) * int(num2)
    divd2 = int(num1) / int(num2)
    sub2 = int(num1) - int(num2)

# Comparare operator strings 
# If input is correct, evaluate operand variables based on operator
    if num1.isdigit() and num2.isdigit():
        if oper is not "*" or "/" or "+" or "-":
            print("No strings or ints for the operator")
        else:
            pass
        if oper is "*":
            print(mult2)
        elif oper is "/":
            print(divd2)
        elif oper is "+":
            print(add2)
        elif oper is "-":
            print(sub2)
        else:
            return print("Try again")

# Call the function
calculate_me()
print()
calculate_me()
print()

0
投票

如果有人有兴趣用这个将字符串字符映射到操作数的概念来解决问题。查看这个可能有用的 leetcode 问题:https://leetcode.com/problems/evaluate-reverse-polish-notation/

© www.soinside.com 2019 - 2024. All rights reserved.