首页 > 解决方案 > Python将包含列表元组的字符串解包到变量

问题描述

嗨,伙计们,我一直在努力如何将字符串解包到变量是一个带有列表和浮点数的元组。

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/

标签: pythonlisttuplesstatsmodelsunpack

解决方案


你可以这样做:

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]分别访问值。


推荐阅读