Convert a string to a list of floats (in python)

后端 未结 5 1837
别那么骄傲
别那么骄傲 2021-01-29 09:51

For data storage purposes I am trying to recover lists of floats from a .txt file. From the string like:

a = \'[1.3, 2.3, 4.5]\'

I want to recover:<

相关标签:
5条回答
  • 2021-01-29 09:58

    well if you are sure that your input data is of type, a = '[1.3, 2.3, 4.5]' then you could use the eval command and assign it to same or a different variable.

    a = '[1.3, 2.3, 4.5]'
    b=eval(a)
    print(b.__class__)  # to know if b is of type list or not
    
    0 讨论(0)
  • 2021-01-29 10:08

    You can also use a more manual way:

    [eval(x) for x in '[1.3, 2.3, 4.5]'.strip("[").strip("]").split(",")]
    Out[64]: [1.3, 2.3, 4.5]
    
    0 讨论(0)
  • 2021-01-29 10:09

    You could use json

    import json
    a = '[1.3, 2.3, 4.5]'
    json.loads(a)
    
    0 讨论(0)
  • 2021-01-29 10:17

    Use the ast module.

    Ex

    import ast
    print(ast.literal_eval('[1.3, 2.3, 4.5]'))
    

    Output:

    [1.3, 2.3, 4.5]
    
    0 讨论(0)
  • 2021-01-29 10:20
    a = a.split(",")
    a[0] = a[0][1:]
    a[-1] = a[-1][:-1]
    a = [float(i) for i in a]
    

    This should work :)

    0 讨论(0)
提交回复
热议问题