Alexander Hallgren
Alexander Hallgren

Reputation: 15

Python - How to check values in a sublist

I'm trying to append a sublist to a larger list of the same type of sublist.

Sublist:

[x-value,y-value, i, 100]

However, I would like my code to check if there is already a sublist that has the same x-value and y-value before adding it, so that, in this case, I don't have overlapping trees (don't ask).

This is how i'm building the list:

food = []
 for i in range(amount): 
        food.append([
            randint(100, 700), #X
            randint(100, 700), #Y
            i, #identifier
            100]) #energy

Upvotes: 0

Views: 280

Answers (3)

Nuclearman
Nuclearman

Reputation: 5304

Aside from using "in", or a dictionary sorting them lexicographically might be better way to go. Then use a 2D binary search to find the what you seek.

Though this probably only useful if you're expecting a lot of duplicates, otherwise a simple linear search would be sufficient.

Note: Originally, sort by distance was suggested, upon reflection, this sort isn't very helpful in the situation.

Upvotes: 0

scripts
scripts

Reputation: 1470

food = []
for i in range(amount):
    x,y = randint(100, 700),randint(100, 700)
    value = [x,y,i,100]
    if  all([True if x[0]!=x and x[1]!=y else False for x in food]): #check for duplicated x,y
        food.append(value)

Upvotes: 0

Platinum Azure
Platinum Azure

Reputation: 46193

If you're trying to ensure uniqueness of the (x, y) values and you have data to associate with them, this is the perfect use case for a dictionary:

food = {}
for i in range(amount):
    coords = randint(100, 700), randint(100, 700)
    if coords not in food:
        food[coords] = [
            i,   #identifier
            100, # energy
        ]

Upvotes: 1

Related Questions