Home > other >  How do I convert a text file containing a list of lists to a string?
How do I convert a text file containing a list of lists to a string?

Time:08-24

The .txt file has a string like this:

[[1.0,2.0,3.0],[4.0,5.0,6.0],[7.0,8.0,9.0]]9.5

My goal is to separate that final number from the list and then turn each of them into a list of lists and a float respectively. I've managed to seperate them but they are still strings and I can't convert them... Here's the code I have:

def string_to_list(file):

for i in os.listdir(path): 
    if i == file:
        openfile = open(path5 '/'  i, 'r')
        values = openfile.read()
        p = ']]'
        print(values)
        print()
        bef, sep, after= values.partition(p)
        string1 = values.replace(after,'')
        print(string1)
        print()
        print(after)

The output is, using the previous exemple:

[[1.0,2.0,3.0],[4.0,5.0,6.0],[7.0,8.0,9.0]]9.5

[[1.0,2.0,3.0],[4.0,5.0,6.0],[7.0,8.0,9.0]]

9.5

But they are all strings yet. How can I make this work? Thank you

CodePudding user response:

ast.literal_eval can do this. json.loads could, as well.

import ast
s = "[[1.0,2.0,3.0],[4.0,5.0,6.0],[7.0,8.0,9.0]]9.5"
i = s.rfind(']')
l = ast.literal_eval(s[:i 1])
o = float(s[i 1:])
print(l, o)

CodePudding user response:

Here is a simple way that only uses list append and loops:

x = list(a[1:len(a)-1]) # remove the outisde brackets
res = []
tmp = []
for e in x:
    if e == ']':
        res.append(tmp)
        tmp = []
        continue
    if e not in ('[', ',', ' ', ''):
        tmp.append(int(e))

CodePudding user response:

You can also use the eval() function after getting the string1 and after values in your code.

myList = eval(string1) #type(myList) will give you list
myFloat = eval(after) #type(myFloat) will give you float
  • Related