Python 将包含列表元组的字符串解压到变量
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
这是为了加载 statsmodels.tsa.holtwinters.ExponentialSmoothing
使用来自 https://machinelearningmastery.com/how-to-grid-search-triple-exponential-smoothing-for-time-series-forecasting-in-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
大家好,我一直在苦苦思索如何将字符串解包为变量,即带有列表和浮点数的元组。
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/
的网格搜索模型你可以这样做:
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