0

Is there a way of getting the index of an instance in an instance array by only knowing a property of that object?

I have something like this:

class NodeGene:
     def __init__(self):
        self.__initBias()

     def __initBias(self):
        #Creates a random bias and assigns it to self.bias

class ConnectionGene:
     #nodeIn and nodeOut are instances of NodeGene
     def __init__(self, nodeIn, nodeOut, innovationNumber):
        self.nodeIn = nodeIn
        self.nodeOut = nodeOut
        self.innovationNumber = innovationNumber
        self.__initWeight()

    def __initWeight(self):
        #Creates a random weight and assigns it to self.weight


class Genome:
     def __init__(self, connections):
        #connections is an array of ConnectionGene instances
        self.connections = connections

How do I get the index of a ConnectionGene in connections if I have the nodeIn and the innovationNumber of the instance I am looking for?

3
  • When you say "array", do you mean that you are using Numpy? Or are you talking about the built-in list type? Commented Sep 17, 2020 at 19:15
  • What should happen if more than one instance has a matching property value? Commented Sep 17, 2020 at 19:16
  • I am using the python list. If more than one instance has all the same properties then raise an error Commented Sep 17, 2020 at 19:20

2 Answers 2

1

Suppose conn_list is a list of ConnectionGene instances. Then you have a few options:

idx = None
for i, c in enumerate(conn_list):
    if c.nodeIn == 0 and c.innovationNumber == 0:
        idx = i
        break

or

idx_list = [i for i, c in enumerate(conn_list) if c.nodeIn == 0 and c.innovationNumber == 0]

or

idx = next(i for i, c in enumerate(conn_list) if c.nodeIn == 0 and c.innovationNumber == 0)

If you will do this many times, it's probably better to make a reference dictionary and do fast lookups there:

dct = {(c.nodeIn, c.innovationNumber): i for i, c in enumerate(conn_list)}
...
idx = dct[0, 0]    # very fast
Sign up to request clarification or add additional context in comments.

Comments

1

The following is one way you can do that. I'm not sure where you want your code called, so I'll just refer to connections as "connections" below.

indices = [index for index, elem in enumerate(connections) if elem.nodeIn == ___ if elem.innovationNumber == ____]
if indices:
    return indices[0]
return -1

Just fill in the blanks. Obviously you can change whether you want to return first index or just all the indices.

If you want to check if nodeIn is the same object instance as another NodeGene, you can use is instead of ==. If you are using ==, you can define the __eq__ method on the NodeGene class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.