简体   繁体   English

Python - 文件中的元组列表

[英]Python - list of tuples from file

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. 我已经完成了一些相当密集的计算,并且我无法将结果保存在pickle中(递归深度除外),因此我被迫打印所有数据并将其保存在文本文件中。

Is there any easy way to now convert my list of tuples in text to well... list of tuples in python? 有没有简单的方法现在将我的文本列表转换为好... 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() : 你可以使用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 ); 首先,我用[1:-1]删除开始和结束方括号,我替换), 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 ) . 所以它不会被元组中的逗号分开,因为它们之前没有a ) Inside the loop I'm using [1:-1] to remove the parenthesis this time and splitting by the commas. 在循环内部我使用[1:-1]来删除括号,并用逗号分割。 The map part is to convert the numeric str s into int s and I'm appending them as a tuple . map部分是将数字str转换为int s,我将它们作为tuple附加。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM