简体   繁体   English

Python 将包含列表元组的字符串解包为变量

[英]Python Unpack String containing Tuple of List to variables

Hi guys I have been strugling how to unpack a string to varibles is a tuple with a list and a float.嗨,伙计们,我一直在苦苦思索如何将字符串解压为变量是一个带有列表和浮点数的元组。

model_parameters="('[None, False, None, 12, False, True]', 18.837459797657008)"

but the output i need must be in this form但我需要的输出必须是这种形式

output=[None, False, None, 12, False, True]
error=18.837459797657008
a,b,c,d,e,f=output

this is for load the statsmodels.tsa.holtwinters.ExponentialSmoothing with the grid searched model from https://machinelearningmastery.com/how-to-grid-search-triple-exponential-smoothing-for-time-series-forecasting-in-python/这是为了使用来自https://machinelearningmastery.com/how-to-grid-search-triple-exponential-smoothing-for-time-series-forecasting-in-的网格搜索模型加载 statsmodels.tsa.holtwinters.ExponentialSmoothing Python/

you can do something like this:你可以这样做:

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]

first, we define a function to convert your string to a tuple, after a=parse_tuple(t) , a[1] will be 18.837459797657008 , then we convert the other element to list, you can use a[i] to access values respectively.首先,我们定义一个函数将你的字符串转换为元组,在a=parse_tuple(t)a[1]将是18.837459797657008 ,然后我们将另一个元素转换为列表,你可以分别使用a[i]访问值.

You can use ast.literal_eval twice:你可以使用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

This is easiest for you using Python eval .这对您使用 Python eval 来说是最简单的。 Where the expression argument is parsed and evaluated as a Python expression其中表达式参数被解析并评估为 Python 表达式

Look here:看这里:

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)

Outputs:输出:

18.837459797657008
None False None 12 False True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM