Home > Net >  String inside a list of lists
String inside a list of lists

Time:11-29

I have a problem with a data, and I must read a text file that contains data from a list of lists.

with open('ej11.txt') as f:
    lines = f.readlines()
    

To read the file correctly I must eliminate the first two elements [' and the last two ']. I have tried with the "pop" method, but by doing so all data are eliminated.

Is there any practical way of being able to solve this? Thanks.

My data is like this:

["[[[1, 21, 13, 14, 15, 0.0, 3.0, 'W'], [2, 24, 16, 17, 18, 4.0, 3.0, 'W']], 8, 2]"]

My data should be like this:

[[[1, 21, 13, 14, 15, 0.0, 3.0, 'W'], [2, 24, 16, 17, 18, 4.0, 3.0, 'W']], 8, 2]

CodePudding user response:

Try using ast.literal_eval:

import ast

d = ["[[[1, 21, 13, 14, 15, 0.0, 3.0, 'W'], [2, 24, 16, 17, 18, 4.0, 3.0, 'W']], 8, 2]"]
data = ast.literal_eval(d[0])

Output:

[[[1, 21, 13, 14, 15, 0.0, 3.0, 'W'], [2, 24, 16, 17, 18, 4.0, 3.0, 'W']],
 8,
 2]
  • Related