operation = ['/','*','+','-']
a =5
b= 2
for op in operation:
output = a+op+b
print output
這裏的輸出我得到的是在循環算術
5/2
5*2
5+2
5-2
,但我想
2.5
10
7
3
什麼是做到這一點?
operation = ['/','*','+','-']
a =5
b= 2
for op in operation:
output = a+op+b
print output
這裏的輸出我得到的是在循環算術
5/2
5*2
5+2
5-2
,但我想
2.5
10
7
3
什麼是做到這一點?
最簡單的方法是使用符號映射到執行的操作,可在operator
發現功能的詞典模塊。
import operator
d = { '+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.div }
operation = d.keys()
a = 5
b = 2
for op in operation:
output = d[op](a, b)
print output
爲此,您可以使用eval
功能:
print eval(output)
注:即使它的危險eval
評估任何字符串中。此外,由於你事先知道你的運營商,您可以使用operators模塊:
import operators
operation = [operators.div, operators.mul, operators.add, operators.sub]
a = 5
b = 2
for op in operation:
output = op(a, b)
print output
使用operator
模塊:
a, b = 5, 2
for op in (operator.div, operator.mul, operator.add, operator.sub):
print(op(a, b))
'輸出= EVAL(STR(浮動的(a))+ OP + STR(浮動(B)))' – Jakob 2014-10-29 12:14:25
到底爲什麼你期望例如'「5」+「/」+「2」'爲'2.5'?這只是一個字符串,它不會被神奇地評估爲一個計算(更不用說,在Python 2.x中,計算結果爲'2')。 – jonrsharpe 2014-10-29 12:16:17