如何将字符串"+"
转换为运算符 plus?
问问题
103781 次
8 回答
128
使用查找表:
import operator
ops = { "+": operator.add, "-": operator.sub } # etc.
print(ops["+"](1,1)) # prints 2
于 2009-11-16T08:09:15.493 回答
34
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())))
于 2009-11-16T08:09:34.280 回答
11
您可以尝试使用 eval(),但如果字符串不是来自您,则很危险。否则,您可能会考虑创建字典:
ops = {"+": (lambda x,y: x+y), "-": (lambda x,y: x-y)}
等等......然后打电话
ops['+'] (1,2)
或者,对于用户输入:if ops.haskey(userop):
val = ops[userop](userx,usery)
else:
pass #something about wrong operator
于 2009-11-16T08:09:16.967 回答
9
如何使用查找字典,但使用 lambdas 而不是运算符库。
op = {'+': lambda x, y: x + y,
'-': lambda x, y: x - y}
然后你可以这样做:
print(op['+'](1,2))
它会输出:
3
于 2019-10-25T00:16:39.493 回答
5
每个算子都有对应的魔术方法
OPERATORS = {'+': 'add', '-': 'sub', '*': 'mul', '/': 'div'}
def apply_operator(a, op, b):
method = '__%s__' % OPERATORS[op]
return getattr(b, method)(a)
apply_operator(1, '+', 2)
于 2016-06-29T09:29:48.600 回答
1
在安全的情况下使用eval()
(不在服务器等):
num_1 = 5
num_2 = 10
op = ['+', '-', '*']
result = eval(f'{num_1} {op[0]} {num_2}')
print(result)
输出:15
于 2021-06-25T10:48:15.940 回答
0
我了解您想要执行以下操作: 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)
于 2018-10-20T13:28:53.543 回答
0
我遇到了同样的问题,使用 Jupyter Notebook,我无法导入操作员模块。所以上面的代码帮助我了解了但无法在平台上运行。我想出了一种使用所有基本功能的有点原始的方法,它是这样的:(这可能会被大量改进,但它是一个开始......)
# 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()
于 2019-04-11T13:50:36.537 回答