列表python中的对象比较,带有索引值
假设我有一节课列表python中的对象比较,带有索引值,python,list,object,Python,List,Object,假设我有一节课 class Foo: def __init__(self, item1, item2): self.item1 = item1 self.item2 = item2 以及该类的对象列表 object1 = Foo (1,2) object2 = Foo (1,2) object3 = Foo (1,3) objectlist = [object1, object3] 我想知道object2的列表中是否有相同项的object2,然后我
class Foo:
def __init__(self, item1, item2):
self.item1 = item1
self.item2 = item2
以及该类的对象列表
object1 = Foo (1,2)
object2 = Foo (1,2)
object3 = Foo (1,3)
objectlist = [object1, object3]
我想知道object2的列表中是否有相同项的object2,然后我想得到它的索引。在本例中,索引为0
我可以自己做
def __eq__ (self, other):
return (self.item1 == other.item1) and (self.item2 == other.item2)
和一个for循环。因为我可以逐个检查每个索引,如果它等于那个对象,就可以得到索引。但是我可以用更为冗长的方式来做吗?问题是,您是否要区分不同的对象,但包含相同值的
item1
和item2
如果是,则不必检查对象的内容。而是依赖于类的每个实例的不同标识符(id(obj)
):
object2 in objectlist
如果不是,那么你的方法(几乎)是正确的,我不知道还有更好的方法。在您的情况下,您没有严格检查两个对象的类是否相同,而是检查它们在结构上是否相同(即它们具有相同的成员item1
和item2
)
您可能还想查看以下问题的答案:怎么样
class Foo:
def __init__(self, item1, item2):
self.item1 = item1
self.item2 = item2
def __eq__ (self, other):
return (self.item1 == other.item1) and (self.item2 == other.item2)
object1 = Foo (1,2)
object2 = Foo (1,2)
object3 = Foo (1,3)
objectlist = [object1, object3]
try:
index_value = objectlist.index(object2)
print(index_value)
except ValueError:
index_value = -1
print(index_value)
你是说objectlist中的object2
,您可能还想实现您的\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
。你是说这是我的朋友?也许我遗漏了什么,但结果得到了-1。@MericOzcan\uuuuu eq\uuuu
需要缩进,就像这样,它不是类的一部分。我更改了它,谢谢@mkiever。现在应该能用了谢谢你就是这样吗?O。o@MericOzcan这是一种按照你说的做的方式,是的。