【问题标题】:Python two-dimensional array - changing an element [closed]Python二维数组 - 改变一个元素[关闭]
【发布时间】:2014-01-10 04:20:05
【问题描述】:

我有这个 7x7 的二维数组:

l=[[1, 1, 1, 1, 1, 1, 1],
  [1, 0, 2, 0, 0, 0, 1],
  [1, 0, 0, 0, 0, 0, 1],
  [1, 0, 0, 0, 0, 0, 1],
  [1, 0, 0, 0, 0, 0, 1],
  [1, 0, 0, 0, 0, 0, 1],
  [1, 1, 1, 1, 1, 1, 1]]

如您所见,l[1][2]=2。当我打印它时,该元素被正确打印。这里没问题。但是当我尝试将它从“2”更改为“3”或任何其他数字时,程序会更改该列(在本例中为第 3 列)上的所有元素,但第一个和最后一个元素除外。例如,如果我输入以下代码:

l[1][2]=5

然后打印二维数组,我得到了:

l=[[1, 1, 1, 1, 1, 1, 1],
  [1, 0, 5, 0, 0, 0, 1],
  [1, 0, 5, 0, 0, 0, 1],
  [1, 0, 5, 0, 0, 0, 1],
  [1, 0, 5, 0, 0, 0, 1],
  [1, 0, 5, 0, 0, 0, 1],
  [1, 1, 1, 1, 1, 1, 1]]

我选择的每个元素都会发生这种情况。它不仅更改了该元素,还更改了整个列。 有谁知道可能是什么问题?谢谢!

【问题讨论】:

  • 我无法复制它。你能在python解释器中自己运行所有这些吗?你用的是哪个python?
  • 这毫无意义,即使你有一个 NumPy 矩阵或对同一个列表的多个引用。您能给我们看一个实际的口译会话吗?
  • 你能告诉我们你是如何实际构建开始列表的吗?我假设您不小心存储了对同一个列表的多个引用。
  • @mgilson:可能,但这仍然不会产生所示的输出。这可能是因为显示的输出不是 OP 实际得到的。
  • @user2357112 -- 是的,我非常怀疑输出是 OP 实际得到的。如果不是第一行,列表的构造可能类似于l = [a, b, b, b, b, b, c] ...

标签: python arrays


【解决方案1】:

即使您描述的行为(如您所描述的那样)是不可能的,我也会对此进行尝试。

如果您创建一个列表,您需要确保每个子列表都是不同的列表。考虑:

a = []
b = [a, a]

在这里,我创建了一个列表,其中两个子列表都是完全相同的列表。如果我改变一个,它会出现在两个。例如:

>>> a = []
>>> b = [a, a]
>>> b[0].append(1)
>>> b
[[1], [1]]

您会经常在使用 * 运算符初始化的列表中看到这种行为:

a = [[None]*7]*7

例如

>>> a = [[None]*7]*7
>>> a
[[None, None, None, None, None, None, None], [None, None, None, None, None, None, None], [None, None, None, None, None, None, None], [None, None, None, None, None, None, None], [None, None, None, None, None, None, None], [None, None, None, None, None, None, None], [None, None, None, None, None, None, None]]
>>> a[0][1] = 3
>>> a
[[None, 3, None, None, None, None, None], [None, 3, None, None, None, None, None], [None, 3, None, None, None, None, None], [None, 3, None, None, None, None, None], [None, 3, None, None, None, None, None], [None, 3, None, None, None, None, None], [None, 3, None, None, None, None, None]]

解决方法是不要在外部列表中使用* 7(内部列表可以,因为None 是不可变的):

a = [[None]*7 for _ in range(7)]

例如:

>>> a = [[None]*7 for _ in range(7)]
>>> a[0][1] = 3
>>> a
[[None, 3, None, None, None, None, None], [None, None, None, None, None, None, None], [None, None, None, None, None, None, None], [None, None, None, None, None, None, None], [None, None, None, None, None, None, None], [None, None, None, None, None, None, None], [None, None, None, None, None, None, None]]

【讨论】:

  • 谢谢。这就是问题所在。我用你的建议解决了。
  • 非常感谢!我浪费了 3 个小时试图调试它。
  • 感谢您的回答。
【解决方案2】:

您的列表构建错误。

中间的项目都引用同一个列表,所以更新一个会导致更改反映在其他项目中

如果你展示你用来构建列表的代码,我可以告诉你如何修复它。

或者

l = [sublist[:] for sublist in l]

在您开始修改列表之前,会将所有这些解耦到新列表中

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    • 2011-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多