使用SequenceMatch进行列表对齐的自定义项

2024-05-29 02:19:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用SequenceMatcher来对齐两个列表。每个列表的项不是元组就是整数。要求是,包含特定整数的元组被视为相等。 例如:

(1, 2, 3) == 1 #True
(1, 2, 3) == 2 #True

为此,我决定重写元组的相等方法:

class CustomTuple(tuple):
    def __eq__(self, other):
        default_eval = super(CustomTuple, self).__eq__(other)
        if default_eval is not True:
            return self.__contains__(other)
        return default_eval

以下是我的示例数据:

x = [22, 16, 11, 16, CustomTuple((11, 19, 20)), 16]
y = [22, 16, CustomTuple((11, 19, 20)), 16, CustomTuple((11, 19, 20)), 16]

使用SequenceMatcher,我期望比率为1.0(相等)。 但结果是:

>>> sm = SequenceMatcher(None, x, y)
>>> sm.ratio()
0.666666666667

但是,当我尝试使用“==”运算符比较列表时,结果是相等的:

>>> x == y
True

有人能指出哪里出了问题吗? 谢谢。你知道吗


Tags: 方法selftruedefault列表returneval整数

热门问题