【问题标题】:Python - Erroneous result for two different matrixes in nested for loopPython - 嵌套for循环中两个不同矩阵的错误结果
【发布时间】:2013-11-22 10:40:45
【问题描述】:

我在嵌套循环中遇到矩阵运算问题。在发布这个问题之前,我查看了 stackoverflow,我发现的所有主题都只处理了一个矩阵。

我的循环尝试计算两个矩阵,第一个中的每个元素为 2,第二个中的每个元素为 1。然而,相同的矩阵作为输出给出。

我试图用一个矩阵复制循环,但给出了相同的错误结果。

感谢您的帮助!

dummy_matrix = [[0 for x in range(2)] for x in range(2)]
other_matrix = dummy_matrix
  for x in range(2):
   for i in range(2):
    dummy_matrix[x][i] = 2
    other_matrix[x][i] = 1
print 'dummy_matrix =',dummy_matrix
print 'other_matrix =',other_matrix
The answer is
dummy_matrix = [[1, 1], [1, 1]] # expected result : [[2, 2], [2, 2]]
other_matrix = [[1, 1], [1, 1]]

【问题讨论】:

  • 请不要在您的问题中添加“已解决”。我们已经知道您得到了对您有帮助的答案,这就是左边距中的 green check mark 所表示的。

标签: python for-loop matrix nested


【解决方案1】:

当你写作时

other_matrix = dummy_matrix

您要求 Python 将名称 other_matrix 绑定到 dummy_matrix 绑定到的同一对象。所以

dummy_matrix[x][i] = 2
other_matrix[x][i] = 1   # overwrites the previous value

做事

other_matrix = [[0 for x in range(2)] for x in range(2)]

改为。

【讨论】:

  • 在什么情况下binding 会发生?因为当我对整数这样做时,>>> y = 1 >>> x = y >>> x+=1 >>> x 2 >>> y 1 >>> 并非如此。你能指点我一些官方资源吗?
  • 非常感谢蒂姆!现在效果很好,你拯救了我的周末!
  • @tMJ:是的,确实如此。但是您在示例中做了不同的事情(将名称重新绑定到新对象),而 OP 的代码正在就地修改对象。 x += 1 表示“取x 的值,加1,然后将x 绑定到结果”。 x[0] = 2 表示“将x 的第一个元素更改为2”。
  • 感谢@TimPietzcker 的帮助,但我离理解这一点还差得很远。您能否指点我一些可以阅读此内容的资源,或者告诉我它叫什么,以便我自己查找。
  • @tMJ:当然:Net Batchelder 写了一篇很棒的博客文章:nedbatchelder.com/text/names.html
【解决方案2】:

问题出在这一行

other_matrix = dummy_matrix

您不是使用此行创建dummy_matrix 的副本,而是使other_matrix 也指向dummy_matrix 也指向的同一个列表。要实际创建副本,您可以使用像这样的切片符号

other_matrix = dummy_matrix[:]

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-25
相关资源
最近更新 更多