gpt4 book ai didi

python - 引用被 Python 中的 pickling 弄乱了

转载 作者:太空宇宙 更新时间:2023-11-04 09:01:06 25 4
gpt4 key购买 nike

我在 python 中对同一个列表进行了两次引用

x = y = []

然后我用 pickle.dump 将它们 pickle 到一个文本文件中,但是当我用 pickle.load 再次加载它们时,它们变成了两个具有不同内存的不同列表地址。如何在 pickle 过程中保持引用关系?

最佳答案

如果您将 xy 作为两个单独的列表进行 pickle,那么当您对它们进行 unpickle 时,它​​们将不会共享引用,无论它们之前是否这样做; 对象,而不是引用,被 pickle :

>>> import pickle
>>> x = y = [1, 2]
>>> with open('test.txt', 'w') as f:
pickle.dump(x, f)
pickle.dump(y, f)


>>> with open('test.txt') as f:
x = pickle.load(f)
y = pickle.load(f)


>>> x == y
True
>>> x is y
False

如果您希望两个名称在您加载后共享引用,您可以pickle一个容器:

>>> x = y = [1, 2]
>>> with open('text.txt', 'w') as f:
pickle.dump([x, y], f)


>>> with open('text.txt') as f:
x, y = pickle.load(f)


>>> x == y
True
>>> x is y
True

但是你也可以只选择一个列表!

关于python - 引用被 Python 中的 pickling 弄乱了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25386433/

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