Python列表在应该的时候不相等

2024-09-29 21:28:48 发布

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

有人能解释一下为什么这两个列表不相等吗?我的意思是输出应该是真的,但它的输出是假的。为什么?

    # CASE 1
    list1 = []
    for item in [self.home_btn, self.secret_dir_btn, self.info_btn]:
        list1.append(QPropertyAnimation(item, b"size"))

    # CASE 2
    self.home_btn_anim = QPropertyAnimation(self.home_btn, b"size")
    self.secret_dir_btn_anim = QPropertyAnimation(self.secret_dir_btn, b"size")
    self.info_btn_anim = QPropertyAnimation(self.info_btn, b"size")
    list2 = [self.home_btn_anim, self.secret_dir_btn_anim, self.info_btn_anim]

    # Output
    print(list1 == list2)
    # Further code

另外,如果我使用案例1来创建列表,我的后续代码将无法正常工作。但是使用案例2创建列表可以使代码正常工作。为什么?我该怎么解决呢


Tags: selfinfohome列表sizesecretdiritem
2条回答

首先,介绍python如何比较sequences

Sequences of the same type also support comparisons. In particular, tuples and lists are compared lexicographically by comparing corresponding elements. This means that to compare equal, every element must compare equal and the two sequences must be of the same type and have the same length.

因此,每个元素必须等于另一个序列中对应的元素。如何检查对象的相等性?如果一个对象未实现^{},则该类型的两个对象之间的比较仅检查两个对象是否完全相同。与中一样,对同一对象的引用-这是is操作符所做的

class Foo():
    pass

a = Foo()
b = Foo()

print(a is a)
# prints true
print(a is b)
# prints false

由于^{}没有实现__eq__,因此只能执行is检查。这显然会导致不同对象引用的错误

如果愿意,可以扩展QPropertyAnimation并实现自己的__eq__-

class MyQPropertyAnimation(QPropertyAnimation):
    def __eq__(self, other):
        if not isinstance(other, QPropertyAnimation):
            # Don't compare against other types
            return NotImplemented
        # Check if the properties `target` and `propertyName` are equal for both objects
        return self.target == other.target and self.propertyName == other.propertyName

但请注意,为动画对象实现相等可能并不理想。但是,如果您严格地希望基于这些属性的相等性用于您的用例,那么这可能很好

正如他们已经向您指出的,序列之间的比较是逐元素进行的,考虑到您试图做的是比较QPropertyAnimation

另一方面,由于设计原因,QoObject不具有可比性,因为它们处理许多内部状态,这意味着即使它们具有相同的属性,它们的行为方式也不相同。QPropertyAnimation是QObject,因此它们也继承了该限制

考虑到这一点,不建议实现__eq__方法,因为它与预定义的设计相矛盾,相反,如果要比较某些属性,请创建一个按属性比较属性的方法:

def compare_animations(animation1, animation2):
    return (
        animation1.target() is animation2.target()
        and animation1.propertyName() == animation2.propertyName()
    )
equals = all([compare_animations(anim1, anim2) for anim1, anim2 in zip(list1, list2)])
print(equals)

相关问题 更多 >

    热门问题