1

I have a class, and in a list I hold some instances of the class. Before appending a new instance I want to check if x, y are the same with some other item. If x,y exist already in another instance, I want to make another random pair. When I find a pair that is unique I will append the new instance to the list.

What is the most efficient way to check this by using only a list, and checking inside the for loop??

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)
baskon1
  • 330
  • 1
  • 3
  • 15

3 Answers3

3

Add an __eq__ method for your class 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

Then check

if NewVehicle not in VehicleList:
    VehicleList.append(NewVehicle)

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

Pobe
  • 2,693
  • 1
  • 17
  • 24
1

You can do it for example like this:

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)
jdehesa
  • 58,456
  • 7
  • 77
  • 121
0

You could use the next() function ...

if next( (True for obj in VehiculeList if obj.x == obj_x and obj.y == obj_y), False):
    ... the list already contains x,y ...
Alain T.
  • 40,517
  • 4
  • 31
  • 51