Python程序用于从字符串中计算算术操作

王林
王林 转载
2023-08-19 13:21:19 1027浏览

Python程序用于从字符串中计算算术操作

算术运算是对数值数据类型进行的数学计算。以下是Python允许的算术运算。

  • 加法 (+)

  • 减法 (-)

  • 乘法 (*)

  • Division (/)

  • 地板除法 (//)

  • Modulo (%)

  • 指数运算 (**)

有几种方法可以从字符串中计算算术运算。让我们逐个来看。

使用eval()函数

在Python中,eval()函数会评估作为字符串传递的表达式,并返回结果。我们可以使用这个函数来计算字符串中的算术操作。

Example

的中文翻译为:

示例

在这种方法中,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

实现算术解析和评估

如果我们希望对解析和评估过程有更多的控制,我们可以实现自己的算术解析和评估逻辑。这种方法涉及将字符串表达式分割为单个操作数和运算符,对它们进行解析,并相应地执行算术运算。

Example

的中文翻译为:

示例

在这个例子中,表达式使用split()方法被分割成单个的标记。然后,根据操作符字典中指定的算术运算符,逐个解析和评估这些标记。通过将适当的操作符应用于累积的结果和当前操作数,计算出结果。

def compute_operation(expression):
   operators = {'+': lambda x, y: x + y,
                  '-': lambda x, y: x - y,
                  '*': lambda x, y: x * y,
                  '//m.sbmmt.com/m/': 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

使用 operator 模块

在Python中,我们有operator模块,它提供了与内置Python运算符对应的函数。我们可以使用这些函数根据字符串表达式中的运算符执行算术运算。

Example

的中文翻译为:

示例

在这个例子中,我们定义了一个字典,将操作符映射到它们在operator模块中对应的函数。我们将表达式分割成标记,其中操作符和操作数被分开。然后,我们遍历这些标记,将对应的操作符函数应用于结果和下一个操作数。

import operator
expression = "2 + 3 * 4"
ops = {
   '+': operator.add,
   '-': operator.sub,
   '*': operator.mul,
   '//m.sbmmt.com/m/': 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中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除