如何将字符串"+"
转换为加法运算符?
如何将字符串"+"
转换为加法运算符?
使用查找表:
import operator
ops = { "+": operator.add, "-": operator.sub } # etc.
print(ops["+"](1,1)) # prints 2
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())))
operator
参数与导入的 operator 模块发生了冲突。我猜测你将 get_operator_fn
和 eval_binary_expr
内联了。将 operator
参数更改为其他名称,例如 oper
,并修改所有对它的引用。请参考我的编辑。 - PaulMcGoperator.div
更改为operator.truediv
,并修复所有的打印语句。 - PaulMcGdict
,从而消除了 O(1)
的查找优势。将 dict
定义在函数外部,这样它只会被构建一次。 - ShadowRanger使用查找字典如何?但是使用lambda表达式代替操作库。
op = {'+': lambda x, y: x + y,
'-': lambda x, y: x - y}
然后你可以这样做:
print(op['+'](1,2))
然后它将输出:
3
你可以尝试使用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
eval
(或exec
)。这是一个严重的安全风险。这样做会允许数据的作者在您的计算机上运行任意代码。它很难被沙盒化,而且正确的沙盒化比使用适当的工具更加困难。 - undefined每个操作符都有对应的魔术方法。
OPERATORS = {'+': 'add', '-': 'sub', '*': 'mul', '/': 'div'}
def apply_operator(a, op, b):
method = '__%s__' % OPERATORS[op]
return getattr(b, method)(a)
apply_operator(1, '+', 2)
如果安全的话(不在服务器等环境中),可以使用eval()
:
num_1 = 5
num_2 = 10
op = ['+', '-', '*']
result = eval(f'{num_1} {op[0]} {num_2}')
print(result)
输出: 15
eval
,因为存在安全风险。 - sleepystar96eval
(或exec
)。这是一个严重的安全风险。这样做会允许数据的作者在您的计算机上运行任意代码。它很难被沙盒化,而正确的沙盒化比使用适当的工具更加困难。 - undefined我明白您想要做类似于:
5 + 7
其中所有三个部分将通过变量传递,所以举个例子:
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)
我曾经遇到过同样的问题,使用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()