我有一个课程,在列表中有该课程的一些实例。在追加新实例之前,我要检查x,y是否与其他项目相同。
如果x,y已经存在于另一个实例中,我想再做一个随机对。当我找到一对唯一的对时,我会将新实例追加到列表中。
通过仅使用列表并在for循环内进行检查的最有效方法是什么?
class Vehicle :
def __init__(self, CoordX, CoordY, Z) :
self.X=CoordX
self.Y=CoordY
self.Z=Z
VehicleList=[]
for i in range (1,15+1):
obj_x = randint(1,30)
obj_y = randint (1,20)
obj_z=randint(1,100)
If..#Check if [x,y] of item exists in list and Generate new random
else:
NewVehicle=Vehicle(obj_x,obj_y,obj_z)
VehicleList.append(NewVehicle)
最佳答案
为您的课程__eq__
添加Vehicle
方法
class Vehicle:
def __init__(self, CoordX, CoordY, Z) :
self.X = CoordX
self.Y = CoordY
self.Z = Z
def __eq__(self, other):
return self.X == other.X and self.Y == other.Y and self.Z == other.Z
然后检查
if NewVehicle not in VehicleList:
VehicleList.append(NewVehicle)
相关:Elegant ways to support equivalence ("equality") in Python classes
关于python - 在追加之前如何检查列表中是否已经存在某些项目属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54752831/