从文件中读取 Python 中的元组列表列表

Read list of lists of tuples in Python from file

我想从文件读取和写入元组列表列表。

g_faces = [[(3,2)(3,5)],[(2,4)(1,3)(1,3)],[(1,2),(3,4),(6,7)]]

我用过

但是文件不是人类可读的。有简单的方法吗?

试试 json 模块。

import json

g_faces = [[(3,2), (3,5)],[(2,4), (1,3), (1,3)],[(1,2), (3,4), (6,7)]]

json.dump(g_faces, open('test.json', 'w'))

g_faces = json.load(open('test.json'))

# cast back to tuples
g_faces = [[tuple(l) for l in L] for L in g_faces]