[英]Python Unpack String containing Tuple of List to variables
嗨,伙计们,我一直在苦苦思索如何将字符串解压为变量是一个带有列表和浮点数的元组。
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
这是为了使用来自https://machinelearningmastery.com/how-to-grid-search-triple-exponential-smoothing-for-time-series-forecasting-in-的网格搜索模型加载 statsmodels.tsa.holtwinters.ExponentialSmoothing Python/
你可以这样做:
import ast
def parse_tuple(string):
try:
s = ast.literal_eval(str(string))
if type(s) == tuple:
return s
return
except:
return
t="('[None, False, None, 12, False, True]', 18.837459797657008)"
a=parse_tuple(t)
a=eval('[' + a[0] + ']')[0]
首先,我们定义一个函数将你的字符串转换为元组,在a=parse_tuple(t)
, a[1]
将是18.837459797657008
,然后我们将另一个元素转换为列表,你可以分别使用a[i]
访问值.
你可以使用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 eval 来说是最简单的。 其中表达式参数被解析并评估为 Python 表达式
看这里:
model_parameters = "('[None, False, None, 12, False, True]', 18.837459797657008)"
m = eval(model_parameters)
output = eval(m[0])
error = m[1]
a, b, c, d, e, f = output
print(error)
print(a,b,c,d,e,f)
输出:
18.837459797657008
None False None 12 False True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.