gpt4 book ai didi

python - 属性错误 : Can't pickle local object '.'

转载 作者:行者123 更新时间:2023-12-05 01:23:25 47 4
gpt4 key购买 nike

我正在尝试 pickle 使用以下方法创建的嵌套字典:

collections.defaultdict(lambda: collections.defaultdict(int))

我的简化代码是这样的:

class A:
def funA(self):
#create a dictionary and fill with values
dictionary = collections.defaultdict(lambda: collections.defaultdict(int))
...
#then pickle to save it
pickle.dump(dictionary, f)

但是它给出了错误:

AttributeError: Can't pickle local object 'A.funA.<locals>.<lambda>'

打印字典后显示:

defaultdict(<function A.funA.<locals>.<lambda> at 0x7fd569dd07b8> {...}

我尝试在该函数中使字典成为全局字典,但错误是相同的。我感谢对此问题的任何解决方案或见解。谢谢!

最佳答案

pickle 记录对函数的引用(模块和函数名称),而不是函数本身。 unpickling 时,它将加载模块并按名称获取函数。 lambda 创建匿名函数对象,这些对象没有名称并且加载程序无法找到。解决方案是切换到命名函数。

def create_int_defaultdict():
return collections.defaultdict(int)

class A:
def funA(self):
#create a dictionary and fill with values
dictionary = collections.defaultdict(create_int_defaultdict)
...
#then pickle to save it
pickle.dump(dictionary, f)

关于python - 属性错误 : Can't pickle local object '<locals>.<lambda>' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72339545/

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