我尝试执行以下代码:(在python中)
from difflib import SequenceMatcher as sm
class myint(int):
def __cmp__(self , other):
return 0
def __eq__(self , other):
return True
a = myint(1)
b = myint(2)
c = myint(3)
d = myint(1)
e = myint(2)
f = myint(3)
x = [a,b,c]
y = [f,e,d]
q = sm(None,x,y)正如您所看到的,在这些代码中,我尝试使用一个自定义的比较函数,这样myint的每两个实例就相等。但是,当我使用SequenceMatcher比较相同长度的两个myint列表时,我得到了一个异常的结果:
>>> q.ratio()
1: 0.3333333333333333而不是1.0。我看到SequenceMatcher使用了数字之间的常规比较,而不是我的比较,尽管列表是由"myint“类型的对象组成的。
我如何编写myint类才能使SequenceMatcher返回1.0?
(或者使用具有自定义比较功能的SequenceMatcher的任何其他想法)
发布于 2012-09-30 08:11:02
看起来你遇到的问题是:
y = [f,e,d]应该是
y = [d,e,f]进行此更改时,q.ratio()将返回1
>>> from difflib import SequenceMatcher as sm
>>> class myint(int):
... def __cmp__(self , other):
... return 0
... def __eq__(self , other):
... return True
...
>>> a = myint(1)
>>> b = myint(2)
>>> c = myint(3)
>>> d = myint(1)
>>> e = myint(2)
>>> f = myint(3)
>>> x = [a,b,c]
>>> y = [d,e,f]
>>> q = sm(None,x,y)
>>> q.ratio()
1.0https://stackoverflow.com/questions/12657415
复制相似问题