您可以使用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