【问题标题】:How to calculate mathematical term packed in a string (python)如何计算包含在字符串中的数学项(python)
【发布时间】: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忽略返回值,总是返回Nonestackoverflow.com/a/29456463/2308683
  • 当然是13(捂脸)

标签: python string loops python-3.x


【解决方案1】:

试试这样的:

x = input()
s = '3*x + 4'
print eval(s)

【讨论】:

  • 我不得不稍微调整一下代码,但代码背后的系统工作得非常好!谢谢!
猜你喜欢
  • 1970-01-01
  • 2021-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-13
  • 2017-03-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多