【发布时间】:2016-03-12 13:34:21
【问题描述】:
我遇到了一个问题,多年来一直没有找到解决方案。
代码是这样的:
Df = range(100)
function = '3*x+4'
for i in Df:
listoffunction = list(function) #Will return ['3', '*', ...]
for obj in listoffunction:
if obj == 'x' :
obj = i
resultfori = ''
for part in listoffunction:
resultfori.join(part) #until here everything is fine.
#resultfori is the following: '3*i+4'
#with i the number of Df
这是我的问题:如何计算这个词?我用exec 命令尝试过,但它总是返回None。为什么?例如,如果我是 3 来返回 13,我想要它。你能帮帮我吗?
非常感谢!
【问题讨论】:
-
为什么是 12?
3*3+4可以合理地评估为 13 或 21,但我看不到 12。 -
你听说过 SymPy 吗?你可能想试试
eval而不是exec -
相关:“
exec忽略返回值,总是返回None”stackoverflow.com/a/29456463/2308683。 -
当然是13(捂脸)
标签: python string loops python-3.x