简体   繁体   English

如何将多个字符串运算符转换为数字?

[英]How to convert multiple string operators into numbers?

I have been trying to create a calculator in Python using tkinter, but it is not working out.我一直在尝试使用 tkinter 在 Python 中创建一个计算器,但它不起作用。 I am trying to use the operator library and the eval function.我正在尝试使用运算符库和 eval 函数。

import operator

ops = {
    '+' : operator.add,
    '*' : operator.mul,
}


def eval_binary_expr(op1, oper, op2, get_operator_fn=ops.get):
    op1, op2 = int(op1), int(op2)
    return get_operator_fn(oper)(op1, op2)


print(eval_binary_expr(*("1 + 3 * 4".split())))

Please help me.请帮我。 It just does not work for me.它对我不起作用。 I am a beginner, so I am bad at this.我是初学者,所以我不擅长这个。 Sorry if you think this question was stupid.对不起,如果你认为这个问题很愚蠢。

Think about this: How many items does the list have, that results from "1 + 3 * 4".split() ?想一想:这个列表有多少个项目,是由"1 + 3 * 4".split() How do they line up with the formal parameters of eval_binary_expr ?它们如何与eval_binary_expreval_binary_expr

One common approach to this type of problem, if you want the usual operator precedence, is the shunting-yard algorithm如果您想要通常的运算符优先级,则解决此类问题的一种常见方法是调车场算法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM