大家好,我一直在努力如何将字符串解包为变量,即带有列表和 float 的元组。
model_parameters="('[None, False, None, 12, False, True]', 18.837459797657008)"
但是我需要的输出必须是这种形式
output=[None, False, None, 12, False, True]
error=18.837459797657008
a,b,c,d,e,f=output
这是为了加载 statsmodels.tsa.holtwinters.ExponentialSmoothing 使用网格搜索模型 https://machinelearningmastery.com/how-to-grid-search-triple-exponential-smoothing-for-time-series-forecasting-in-python/
最佳答案
您可以使用 ast.literal_eval
两次:
import ast
model_parameters="('[None, False, None, 12, False, True]', 18.837459797657008)"
list_as_str, error = ast.literal_eval(model_parameters)
output = ast.literal_eval(list_as_str)
a,b,c,d,e,f = output
# We have all the values we want:
print(a, b, c, d, e, f, error)
# None False None 12 False True 18.837459797657008
关于Python 将包含列表元组的字符串解压为变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59437268/