将字符串变成运算符
- 2024-12-27 08:47:00
- admin 原创
- 111
问题描述:
我怎样才能将诸如此类的字符串转换"+"
为加号运算符?
解决方案 1:
使用查找表:
import operator
ops = { "+": operator.add, "-": operator.sub } # etc.
print(ops["+"](1,1)) # prints 2
解决方案 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())))
解决方案 3:
如何使用查找字典,但使用 lambda 而不是运算符库。
op = {'+': lambda x, y: x + y,
'-': lambda x, y: x - y}
然后你可以这样做:
print(op['+'](1,2))
它将输出:
3
解决方案 4:
您可以尝试使用 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
解决方案 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)
解决方案 6:
如果安全的话使用eval()
(不在服务器上等):
num_1 = 5
num_2 = 10
op = ['+', '-', '*']
result = eval(f'{num_1} {op[0]} {num_2}')
print(result)
输出:15
解决方案 7:
我理解您想要执行类似以下操作: 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)
解决方案 8:
我遇到了同样的问题,使用 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()
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD