2

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

jfvcs
  • 21
  • 4

3 Answers3

3

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)
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
1

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))
yuhaigiub
  • 56
  • 4
0

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
Harshith P
  • 24
  • 4
  • 1
    When using eval you must protect your input file very carefully and _never_ use user input in eval function. You can create a huge security vulnerability in your software with this. – ex4 Aug 23 '22 at 05:36
  • 1
    Yes. `eval` has very, very few legitimate uses. Almost everything it can do can be done more safely with `ast.literal_eval` and `json.loads`. – Tim Roberts Aug 23 '22 at 06:23