pythonarraysinstancegenetic-algorithmgenetic-programming

Can I get the index of an object in an instance array by knowing a value of the object?


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?


Solution

  • 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