4

I have completed some rather intensive calculations, and i was not able to save my results in pickle (recursion depth exceded), so i was forced to print all the data and save it in a text file.

Is there any easy way to now convert my list of tuples in text to well... list of tuples in python? the output looks like this:

[(10, 5), (11, 6), (12, 5), (14, 5), (103360, 7), (16, 6), (102725, 7), (17, 6), (18, 5), (19, 9), (20, 6), ...(it continues for 60MB)]
KONAKONA
  • 87
  • 5

2 Answers2

5

You can use ast.literal_eval():

>>> s = '[(10, 5), (11, 6), (12, 5), (14, 5)]'
>>> res = ast.literal_eval(s)
[(10, 5), (11, 6), (12, 5), (14, 5)]
>>> res[0]
(10, 5)
ettanany
  • 15,827
  • 5
  • 37
  • 56
0
string = "[(10, 5), (11, 6), (12, 5), (14, 5), (103360, 7), (16, 6), (102725, 7), (17, 6), (18, 5), (19, 9), (20, 6)]" # Read it from the file however you want

values = []
for t in string[1:-1].replace("),", ");").split("; "):
    values.append(tuple(map(int, t[1:-1].split(", "))))

First I remove the start and end square bracket with [1:-1], I replace ), with ); to be able to split by ; so that the it foesn't split by the commas inside the tuples as they are not preceded by a ). Inside the loop I'm using [1:-1] to remove the parenthesis this time and splitting by the commas. The map part is to convert the numeric strs into ints and I'm appending them as a tuple.

Adirio
  • 4,609
  • 1
  • 12
  • 22