1

我有一个类,在一个列表中我保存了该类的一些实例。在添加新实例之前,我想检查 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)
4

3 回答 3

3

为您的课程添加__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)

相关:在 Python 类中支持等价(“平等”)的优雅方式

于 2019-02-18T18:08:33.003 回答
1

例如,您可以这样做:

from random import randint

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)
    while any(v.X == obj_x and v.Y == obj_y and v.Z == obj_z for v in VehicleList):
        obj_x = randint(1, 30)
        obj_y = randint(1, 20)
        obj_z = randint(1, 100)
    NewVehicle = Vehicle(obj_x, obj_y, obj_z)
    VehicleList.append(NewVehicle)
于 2019-02-18T17:58:58.467 回答
0

您可以使用 next() 函数...

if next( (True for obj in VehiculeList if obj.x == obj_x and obj.y == obj_y), False):
    ... the list already contains x,y ...
于 2019-02-18T18:19:09.267 回答