将python数据结构保存到imp

2024-05-16 15:41:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我的程序创建了一个概率模型,我想保存为一个模块,以便以后导入。我怎样才能以一种可以直接导入的方式保存它?你知道吗

Json适用于dict,但我有不同的数据结构,Pickle似乎不允许直接使用importpprint不打印结构的名称和赋值。你知道吗

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

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)

Tags: 模块pyimport程序json数据结构modelsave
1条回答
网友
1楼 · 发布于 2024-05-16 15:41:30

看看^{}模块。你知道吗

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.

这将不是你想要的方式,但我认为这是一个简单和合理的方式做你想要的。你知道吗

相关问题 更多 >