Skip to main content
 首页 » 编程设计

Python。将 str ('+' ) 转换为数学运算

2025年05月04日10dudu

如何将 str('+') 转化为数学运算? 例如:

a = [0,1,2] # or a = ['0','1','2'] 
b = ['+','-','*'] 
c = int(a[0]+b[0]+a[1]) 

换句话说,如何将 str('-1*2') 转换为 int(),而无需 for i in c: if i == '+': ... 谢谢。

请您参考如下方法:

您还可以使用运算符(operator)模块:

import operator as op 
#Create a mapping between the string and the operator: 
ops = {'+': op.add, '-': op.sub, '*': op.mul} 
 
a = [0,1,2] 
b = ['+','-','*'] 
 
#use the mapping 
c = ops[b[0]](a[0], a[1])