如何在追加之前检查列表中是否已经存在某些项目属性

时间:2019-02-18 17:52:16

标签: python

我有一个课程,并且在列表中保存了该课程的一些实例。在追加新实例之前,我要检查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)

3 个答案:

答案 0 :(得分: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)

相关:Elegant ways to support equivalence ("equality") in Python classes

答案 1 :(得分: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)

答案 2 :(得分: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 ...