pickle 如何知道选择哪个?
how does pickle know which to pick?
我的 pickle 功能正常工作
with open(self._prepared_data_location_scalar, 'wb') as output:
# company1 = Company('banana', 40)
pickle.dump(X_scaler, output, pickle.HIGHEST_PROTOCOL)
pickle.dump(Y_scaler, output, pickle.HIGHEST_PROTOCOL)
with open(self._prepared_data_location_scalar, 'rb') as input_f:
X_scaler = pickle.load(input_f)
Y_scaler = pickle.load(input_f)
不过,我很好奇pickle是怎么知道加载哪个的?这是否意味着所有内容都必须按相同的顺序排列?
哇,我什至不知道你能做到这一点......而且我已经使用 python 很长时间了......所以这在我的书中非常棒,但是你真的不应该这样做这以后会很难处理(特别是如果不是你在处理的话)
我建议只做
pickle.dump({"X":X_scalar,"Y":Y_scalar},output)
...
data = pickle.load(fp)
print "Y_scalar:",data['Y']
print "X_scalar:",data['X']
除非你有一个非常令人信服的理由来保存和加载数据,就像你在你的问题中一样...
编辑以回答实际问题...
它从文件的开头加载到结尾(即按照转储的相同顺序加载它们)
是的,pickle 按保存顺序拾取对象。
直觉上,pickle 在写入(转储)文件时追加到末尾,
并按顺序读取(加载)文件中的内容。
因此,顺序得以保留,允许您按照序列化数据的确切顺序检索数据。
你有的很好。这是 documented feature 泡菜:
It is possible to make multiple calls to the dump() method of the same Pickler instance. These must then be matched to the same number of calls to the load() method of the corresponding Unpickler instance.
这里没有魔法,pickle 是一种非常简单的基于堆栈的语言,可将 python 对象序列化为字节串。 pickle 格式了解对象边界:根据设计,pickle.dumps('x') + pickle.dumps('y')
与 pickle.dumps('xy')
不是相同的字节串。
如果您有兴趣了解有关实施的一些背景知识,this article 是一本易于阅读的书,可以让您对 python pickler 有所了解。
我的 pickle 功能正常工作
with open(self._prepared_data_location_scalar, 'wb') as output:
# company1 = Company('banana', 40)
pickle.dump(X_scaler, output, pickle.HIGHEST_PROTOCOL)
pickle.dump(Y_scaler, output, pickle.HIGHEST_PROTOCOL)
with open(self._prepared_data_location_scalar, 'rb') as input_f:
X_scaler = pickle.load(input_f)
Y_scaler = pickle.load(input_f)
不过,我很好奇pickle是怎么知道加载哪个的?这是否意味着所有内容都必须按相同的顺序排列?
哇,我什至不知道你能做到这一点......而且我已经使用 python 很长时间了......所以这在我的书中非常棒,但是你真的不应该这样做这以后会很难处理(特别是如果不是你在处理的话)
我建议只做
pickle.dump({"X":X_scalar,"Y":Y_scalar},output)
...
data = pickle.load(fp)
print "Y_scalar:",data['Y']
print "X_scalar:",data['X']
除非你有一个非常令人信服的理由来保存和加载数据,就像你在你的问题中一样...
编辑以回答实际问题...
它从文件的开头加载到结尾(即按照转储的相同顺序加载它们)
是的,pickle 按保存顺序拾取对象。
直觉上,pickle 在写入(转储)文件时追加到末尾, 并按顺序读取(加载)文件中的内容。
因此,顺序得以保留,允许您按照序列化数据的确切顺序检索数据。
你有的很好。这是 documented feature 泡菜:
It is possible to make multiple calls to the dump() method of the same Pickler instance. These must then be matched to the same number of calls to the load() method of the corresponding Unpickler instance.
这里没有魔法,pickle 是一种非常简单的基于堆栈的语言,可将 python 对象序列化为字节串。 pickle 格式了解对象边界:根据设计,pickle.dumps('x') + pickle.dumps('y')
与 pickle.dumps('xy')
不是相同的字节串。
如果您有兴趣了解有关实施的一些背景知识,this article 是一本易于阅读的书,可以让您对 python pickler 有所了解。