3 回答
TA贡献1807条经验 获得超9个赞
你可以这样做:
import operator
operations = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv}
char = raw_input('enter your operator:')
a = 1
b = 5
c = operations[char](a, b)
print c
输出 (对于字符 = +)
6
TA贡献1777条经验 获得超3个赞
或使用:
from operator import *
char = raw_input('enter your operator:')
a=1
b=5
c={'+':add,'-':sub,'*':mul,'/':truediv}
print(c[char](a,b))
或者int.some operator name:
char = raw_input('enter your operator:')
a=1
b=5
c={'+':int.__add__,'-':int.__sub__,'*':int.__mul__,'/':int.__truediv__}
print(c[char](a,b))
两种情况的演示输出:
enter your operator:*
5
TA贡献1818条经验 获得超7个赞
像这样:
a=1
b=2
op = '+'
result = eval('{}{}{}'.format(a, op, b)) # result = 3
您还必须将 a 和 b 转换为字符串eval才能工作。
添加回答
举报