通过标识而不是相等性从python列表中删除元素

我正在定义一个Python对象,我希望它具有一个可以调用的方法来在可能出现的各种列表之间移动它。我编写了以下实现:

def transfer(self,source,destination):
   source.remove(self)
   destination.append(self)

但是,我很快发现list.remove的Python实现是通过平等而非身份来实现的;也就是说,如果source中较早的另一个元素的值等于self,则该元素将被删除。

如何实现此目的,以便达到我想要的行为-仅从source中删除引用的确切元素,而不删除任何与其值相等的旧元素?或者,更有可能是实现我的transfer方法的另一种方法?

aidetianshi123456 回答:通过标识而不是相等性从python列表中删除元素

您可以使用is运算符进行操作,它检查身份,即对象是同一对象,而不是相等性:

代码可以通过以下方式查看:

def transfer(self,source,destination):
    for i in range(len(source)):   # check all elements of the list
        # check if element is self ("is" checks not equality but identity)
        # "==" checks identity
        if source[i] is self:  
            element = source.pop(i)  # remove element by index to be sure that it is what we need
            break
    destination.append(element)

一些测试:

def transfer(x,destination):
    for i in range(len(source)):   # check all elements of the list
        # check if element is self ("is" checks not equality but identity)
        # "==" checks identity
        print(source[i])  # will print 4 times to prove that 4th element was taken
        if source[i] is x:

            element = source.pop(i)  # remove element by index to be sure that it is what we need
            break
    destination.append(element)


class Test:
    def __init__(self,x):
        self.x = x

    def __eq__(self,other):
        if self.x == other.x:
            return True
        return False

    def __repr__(self):
        return "Test({})".format(self.x)

x,y,z,a = Test(1),Test(2),Test(3),Test(3)

list_1 = [x,a]
list_2 = []

transfer(a,list_1,list_2)
print(list_1)
print(list_2)

让我知道是否有帮助,随时提出问题。

本文链接:https://www.f2er.com/3140002.html

大家都在问