【问题标题】:Can I get the index of an object in an instance array by knowing a value of the object?我可以通过知道对象的值来获取实例数组中对象的索引吗?
【发布时间】:2021-01-04 17:53:26
【问题描述】:

有没有办法仅通过知道该对象的属性来获取实例数组中实例的索引?

我有这样的事情:

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

如果我有我要查找的实例的 nodeIn 和 innovationNumber,我如何在连接中获取 ConnectionGene 的索引?

【问题讨论】:

  • 当你说“数组”时,你的意思是你正在使用 Numpy 吗?或者你说的是内置的 list 类型?
  • 如果多个实例具有匹配的属性值会怎样?
  • 我正在使用 python 列表。如果多个实例具有所有相同的属性,则引发错误

标签: python arrays instance genetic-algorithm genetic-programming


【解决方案1】:

假设conn_listConnectionGene 实例的列表。那么你有几个选择:

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

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

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

如果您要多次这样做,最好制作一个参考字典并在那里进行快速查找:

dct = {(c.nodeIn, c.innovationNumber): i for i, c in enumerate(conn_list)}
...
idx = dct[0, 0]    # very fast

【讨论】:

    【解决方案2】:

    以下是您可以做到这一点的一种方法。我不确定你想在哪里调用你的代码,所以我将在下面将连接称为“连接”。

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

    只需填空即可。显然,您可以更改是要返回第一个索引还是只返回所有索引。

    如果要检查 nodeIn 是否与另一个 NodeGene 相同的对象实例,可以使用 is 而不是 ==。如果你使用==,你可以在NodeGene类上定义__eq__方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-07
      • 2017-03-26
      • 1970-01-01
      • 2023-04-04
      • 2023-04-08
      • 2017-08-21
      • 2022-06-26
      • 2011-10-26
      相关资源
      最近更新 更多