Python - list of tuples from a file

I did some pretty intense calculations, and I couldn’t save my results in pickle (recursion depth), so I had to print all the data and save it in a text file.

Is there an easy way now to convert a list of tuples to text so that ... a list of tuples in python? The output is as follows:

[(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)]
+4
source share
2 answers

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)
+5
source
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(", "))))

[1:-1], ), );, ; , a ). [1:-1], . map str int, tuple.

0

Source: https://habr.com/ru/post/1688587/


All Articles