如何删除与Python中的对象具有相同属性的对象?

2024-10-06 12:43:13 发布

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

我有一类对象:

class Object :
def __init__(self,id,x,y):
    self.id = id
    self.x = x
    self.y = y

对象的id是唯一的,但对于x和y,它们可能相似:

例如,让我们有4个对象:

ob1 = Object(0, 2.7, 7.3)
ob2 =  Object(1, 2.7, 7.3)
ob3 = Object(2, 3.2, 4.6)
ob4 = Object(3, 2.7, 7.3)

我只想保留x和y不同的对象,例如这里我只想保留ob1ob3ob2ob3ob4ob3
我怎么做呢

谢谢


Tags: 对象selfidobjectinitdefclassob1
2条回答

允许使用技术from here将对象添加到集合中

要在集合中放置对象,对象类需要实现:

  1. eq(…)
  2. 散列(…)

代码

class Object :
  def __init__(self,id,x,y):
    self.id = id
    self.x = x
    self.y = y

  def __eq__(self, other):
    return self.x == other.x and self.y == other.y

  def __hash__(self):
    return hash((self.x, self.y)) # hash of x, y tuple

  def __str__(self):
    return str(vars(self))       # vars converts attributes to dictionary
                                 # str converts dictionary to string 

用法

ob1 = Object(0, 2.7, 7.3)
ob2 =  Object(1, 2.7, 7.3)
ob3 = Object(2, 3.2, 4.6)
ob4 = Object(3, 2.7, 7.3)

set_ = {ob1, ob2, ob3, ob4}  # Place objects in set

# Show unique elements i.e. set
for obj in set_:
  print(obj)

输出

{'id': 2, 'x': 3.2, 'y': 4.6}   # ob2
{'id': 0, 'x': 2.7, 'y': 7.3}   # ob0

如果您不想或由于某种原因无法添加在集合中使用对象所需的方法,则可以使用临时字典查找具有唯一属性集的对象:

ob1 = Object(0, 2.7, 7.3)
ob2 = Object(1, 2.7, 7.3)
ob3 = Object(2, 3.2, 4.6)
ob4 = Object(3, 2.7, 7.3)

uniq = {(o.x, o.y): o for o in [ob1, ob2, ob3, ob4]}.values()

# test - print the object ids
print([o.id for o in uniq]

结果:

[3, 2]

相关问题 更多 >