【问题标题】:list is always set to be equal to another even when not called即使未调用 list 也始终设置为等于另一个
【发布时间】:2020-12-27 02:16:34
【问题描述】:

我有一个循环,其中神经网络设置为等于最佳神经网络。然后,我稍微改变一下神经元列表,并用它计算任何东西,但它同时也设置了最佳神经元列表。这是我的代码的摘录,你可以试试:

for x in range(numberOfGenerations):
    print(neurons)
    print(bestNeurons)
    neurons = bestNeurons
    print(neurons)
    print(bestNeurons)  # Both lists should be the same here
    for y in range(numberOfNeurons):
        weights[y] = random.uniform(0.999, 1.001)
        neurons[y] = weights[y] * neurons[y]

    print(neurons)
    print(bestNeurons)  # They should be different here, because neurons was changed
    if currentGenerationScore > bestScore:
        print("New best score!: ", currentGenerationScore)
        for b in range(numberOfNeurons):
        bestNeurons[b] = neurons[b]
        print(bestNeurons)
        bestScore = currentGenerationScore
        print("Best set of neurons:", bestNeurons)
        bestImageScore = totalImageScore
        bestPlaceboScore = totalPlaceboScore

print(neurons)
print(bestNeurons)

通常,在我的代码块的末尾,列表神经元和 bestNeurons 应该是不同的,但是通过在控制台中打印它们,它们实际上是相等的。我希望在不影响最佳神经元列表的情况下更改神经元列表。谢谢你帮助我。

【问题讨论】:

  • edit您的帖子并将您的代码转换为minimal reproducible example。它目前无法单独运行。请提供所有变量的初始值。
  • 试试neurons = bestNeurons.copy()neurons = list(bestNeurons)
  • (1) 您发布的代码仍然无法运行至少两个不同的错误。 (2) 列表是相等的,因为您专门将它们设置为相同的列表。查看如何制作列表的副本。
  • 成功了。似乎将一个列表设置为直接等于另一个列表会使解释器将其视为一个列表。非常感谢,蒂姆斯。

标签: python list for-loop


【解决方案1】:

“尝试神经元 = bestNeurons.copy() 或神经元 = list(bestNeurons)。- Timus 1 小时前”

【讨论】:

    猜你喜欢
    • 2018-08-23
    • 1970-01-01
    • 1970-01-01
    • 2016-09-01
    • 2016-01-25
    • 2014-08-26
    • 1970-01-01
    • 1970-01-01
    • 2021-04-29
    相关资源
    最近更新 更多