
算术运算是对数值数据类型进行的数学计算。以下是Python允许的算术运算。
加法 (+)
减法 (-)
乘法 (*)
立即学习“Python免费学习笔记(深入)”;
Division (/)
地板除法 (//)
Modulo (%)
指数运算 (**)
有几种方法可以从字符串中计算算术运算。让我们逐个来看。
在Python中,eval()函数会评估作为字符串传递的表达式,并返回结果。我们可以使用这个函数来计算字符串中的算术操作。
在这种方法中,eval() 函数评估表达式"2 + 3 * 4 - 6 / 2"并返回结果,然后将结果存储在变量"result"中。
def compute_operation(expression):
result = eval(expression)
return result
expression = "2 + 3 * 4 - 6 / 2"
result = compute_operation(expression)
print("The result of the given expression:",result)
The result of the given expression: 11.0
如果我们希望对解析和评估过程有更多的控制,我们可以实现自己的算术解析和评估逻辑。这种方法涉及将字符串表达式分割为单个操作数和运算符,对它们进行解析,并相应地执行算术运算。
在这个例子中,表达式使用split()方法被分割成单个的标记。然后,根据操作符字典中指定的算术运算符,逐个解析和评估这些标记。通过将适当的操作符应用于累积的结果和当前操作数,计算出结果。
def compute_operation(expression):
operators = {'+': lambda x, y: x + y,
'-': lambda x, y: x - y,
'*': lambda x, y: x * y,
'/': lambda x, y: x / y}
tokens = expression.split()
result = float(tokens[0])
for i in range(1, len(tokens), 2):
operator = tokens[i]
operand = float(tokens[i+1])
result = operators[operator](result, operand)
return result
expression = "2 + 3 * 4 - 6 / 2"
result = compute_operation(expression)
print("The result of given expression",result)
The result of given expression 7.0
在Python中,我们有operator模块,它提供了与内置Python运算符对应的函数。我们可以使用这些函数根据字符串表达式中的运算符执行算术运算。
在这个例子中,我们定义了一个字典,将操作符映射到它们在operator模块中对应的函数。我们将表达式分割成标记,其中操作符和操作数被分开。然后,我们遍历这些标记,将对应的操作符函数应用于结果和下一个操作数。
import operator
expression = "2 + 3 * 4"
ops = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv,
}
tokens = expression.split()
result = int(tokens[0])
for i in range(1, len(tokens), 2):
operator_func = ops[tokens[i]]
operand = int(tokens[i + 1])
result = operator_func(result, operand)
print("The arithmetic operation of the given expression:",result)
The arithmetic operation of the given expression: 20
以上就是Python程序用于从字符串中计算算术操作的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号