Search code examples
pythonlisttuplesstatsmodelsunpack

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/


Solution

  • You can use ast.literal_eval twice:

    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