0
我已創建使用如何將'namedtuple'結構與'pickle'結合使用?
from collections import namedtuple
import random
demand={}
Site_Product=namedtuple("Site_Product", ["site", "product"])
Products=['P1','P2','P3']
for P in Products:
for node in range(1,4): #Suppliers:
sp=Site_Product(site=node, product=P)
demand={sp:random.normalvariate(30, 25)}
然後我想保存這些的情況下,字典的元組我如下可能會使用它以後:
import pickle
PIK = "pickle_SC_detail.dat"
with open(PIK, "wb") as f:
pickle.dump(demand, f)
我有一大堆的錯誤主要是指向我namedtuple結構:
File "C:\Users\Ozgu\Anaconda2\lib\pickle.py", line 1376, in dump
Pickler(file, protocol).dump(obj)
File "C:\Users\Ozgu\Anaconda2\lib\pickle.py", line 224, in dump
self.save(obj)
File "C:\Users\Ozgu\Anaconda2\lib\pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "C:\Users\Ozgu\Anaconda2\lib\pickle.py", line 655, in save_dict
self._batch_setitems(obj.iteritems())
File "C:\Users\Ozgu\Anaconda2\lib\pickle.py", line 668, in _batch_setitems
save(k)
File "C:\Users\Ozgu\Anaconda2\lib\pickle.py", line 331, in save
self.save_reduce(obj=obj, *rv)
File "C:\Users\Ozgu\Anaconda2\lib\pickle.py", line 401, in save_reduce
save(args)
File "C:\Users\Ozgu\Anaconda2\lib\pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "C:\Users\Ozgu\Anaconda2\lib\pickle.py", line 568, in save_tuple
save(element)
File "C:\Users\Ozgu\Anaconda2\lib\pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "C:\Users\Ozgu\Anaconda2\lib\pickle.py", line 754, in save_global
(obj, module, name))
PicklingError: Can't pickle \<class '__main__.Site_Product'\>: it's not found as __main__.Site_Product
有一個變通無論是讓我的字典元組(鑰匙)或記錄我的數據以不昂貴的方式存在,以便它們共存?
複製你的兩個代碼片段,使用Python 2.7.11工作正常 – Skirrebattie
有問題的代碼適用於我在Windows上使用Python 2.7.11。你確定'Site_Product'是在真實代碼的頂層(不在函數或方法中)定義的嗎? – martineau
是的,那肯定是問題所在!他們有不同的功能,我會盡力讓全球化或將它們聯合起來。 – Ozgu