我使用python创建了一个树结构。假设树有根节点、左子节点和右子节点。我需要在需要时访问树。但是在打开文件并运行时会重新创建树。由于我在树中有大量节点,因此娱乐的方法很耗时。请为我提供一个解决方案,以便我可以在需要时存储树、获取和更新(插入或删除节点)。
问问题
153 次
1 回答
0
您可以使用可用于序列化和反序列化 python 对象的pickle模块很容易。
import pickle
tree = {'a': 'b'}
# serializing the data
with open('/path/to/some/file', 'wb') as f:
pickle.dump(tree, f, pickle.HIGHEST_PROTOCOL)
# and deserializing it again
with open('/path/to/same/file', 'rb') as f:
tree = pickle.load(f)
于 2020-06-19T09:17:09.760 回答