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)]
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)
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 str
s into int
s and I'm appending them as a tuple
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.