我有这根绳子:
x = "2x4, 2x5"
我想把它转化为下面的操作:
x = (2 * 4) + (2 * 5)
所以最终结果将是18。
你有什么想法吗? 如果该解决方案能够灵活地处理不同项数的字符串(例如:“2x4,2x5,2x7”),那就太好了!
谢啦!
斯普利特是你的朋友
def compute(equation):
mults = equation.split(",")
_sum = 0
for mult in mults:
terms = mult.split("x")
products = 1
for term in terms:
products *= int(term)
_sum += products
return _sum
您可以使用operator.mul
将这些数字相乘,并使用sum
将它们相加,请尝试以下操作:
from operator import mul
x = "2x4, 2x5, 2x7"
print(sum(mul(*map(int, i.split('x'))) for i in x.split(', ')))
结果:
32
使用Eval
Code def eval_str(s):ss=s.replace(',‘,'+').replace('x','*')#,->; +和“x”->; *
return eval(ss, {}, {}) # make eval safer by setting globals and locals to empty dictionary
用法
x = "2x4, 2x5"
print(eval_str(x))
# Output: 18