# 因为 7.6并非int,而且不用判断字符串转数字,因为str2num此时得到的实参就是个字符而非数字,所以只需要将int(s)改为float(s),无需判断s的type
from functools import reduce def str2num(s): return float(s) def calc(exp): ss = exp.split('+') ns = map(str2num, ss) return reduce(lambda acc, x: acc + x, ns) def main(): r = calc('100 + 200 + 345') print('100 + 200 + 345 =', r) r = calc('99 + 88 + 7.6') print('99 + 88 + 7.6 =', r) main()
Sign in to make a reply
用户7686226831
# 因为 7.6并非int,而且不用判断字符串转数字,因为str2num此时得到的实参就是个字符而非数字,所以只需要将int(s)改为float(s),无需判断s的type