gpt4 book ai didi

python - 保存python数据结构以便稍后导入

转载 作者:太空宇宙 更新时间:2023-11-03 18:25:48 26 4
gpt4 key购买 nike

我的程序创建了一个概率模型,我想将其保存为模块以便稍后导入。如何保存为可以直接导入的方式?

Json 对于字典很有用,但我有不同的数据结构,Pickle 似乎不允许直接使用 import>pprint 不打印结构的名称和分配。

我只想创建一些数据结构:

states = (
'Bound',
'Not-bound'
)

Prob = {
'Bound': 0.45,
'Not-bound': 0.55
}

以某种方式将它们保存到“py”文件中:

with open('model.py', 'wb') as out:
save(states)
save(Prob)

然后,稍后直接导入它们:

import model
print(model.states)

最佳答案

看看pickle模块。

The pickle module implements binary protocols for serializing and de-serializing a Python object structure. “Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the inverse operation, whereby a byte stream (from a binary file or bytes-like object) is converted back into an object hierarchy.

这不会完全按照您想要的方式进行,但我认为这是一种简单合理的方式来完成您想要的事情。

关于python - 保存python数据结构以便稍后导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23231177/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com