我尝试执行以下代码:(在 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 的任何其他想法)
请您参考如下方法:
看起来你遇到的问题是:
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.0
