我正在尝试使用SortedListWithKey工具中的cmp_to_key()函数来将比较函数转换为键函数。但是,cmp_to_key()似乎使我的对象不可拾取,并且我得到以下错误: TypeError: can't pickle functools.KeyWrapper objects
我怎么才能修复它?这是一个重现错误的代码示例:
import pickle
from functools import cmp_to_key
from sortedcontainers import SortedListWithKey
def order_fun(a, b):
if abs(a[0]-b[0]) < 1e-8:
return 0
elif a[0]-b[0] > 0:
return 1
else:
return -1
pickle.loads(pickle.dumps(SortedListWithKey([[1,2], [3,4]], key=cmp_to_key(order_fun))))谢谢!
注意:酸洗在不使用cmp_to_key()函数的情况下工作得很好,但我需要它,因为我的函数不是键函数。
发布于 2017-12-27 09:43:29
问题似乎是cmp_tp_key是now written in C,并且它返回的类既不是可拾取的,也不是可子类的。然而,最初的纯python版本是still maintained in the source,并且非常简单。当它与您的示例一起使用时,它可以正确地工作。当然,明显的缺点是纯python版本比较慢--但是the difference is not huge。
以下是您的示例的工作版本:
import pickle
from sortedcontainers import SortedListWithKey
def order_fun(a, b):
if abs(a[0]-b[0]) < 1e-8:
return 0
elif a[0]-b[0] > 0:
return 1
else:
return -1
class KeyFunc(object):
__slots__ = ['obj']
def __init__(self, obj):
self.obj = obj
def __lt__(self, other):
return order_fun(self.obj, other.obj) < 0
def __gt__(self, other):
return order_fun(self.obj, other.obj) > 0
def __eq__(self, other):
return order_fun(self.obj, other.obj) == 0
def __le__(self, other):
return order_fun(self.obj, other.obj) <= 0
def __ge__(self, other):
return order_fun(self.obj, other.obj) >= 0
__hash__ = None
sl = SortedListWithKey([[1,2], [3,4]], key=KeyFunc)
print(sl)
print(pickle.loads(pickle.dumps(sl)))输出:
SortedListWithKey([[1, 2], [3, 4]], key=<class '__main__.KeyFunc'>)
SortedListWithKey([[1, 2], [3, 4]], key=<class '__main__.KeyFunc'>)https://stackoverflow.com/questions/47985058
复制相似问题