1

可能重复:
关于双循环的简单python代码

我遇到了一个众所周知的问题,即更改列表中的一项。我需要使用固定大小的列表列表。

如果我使用:

In [21]: a=[[2]*2]*3

In [22]: a
Out[22]: [[2, 2], [2, 2], [2, 2]]

In [23]: a[0][0]=1

In [24]: a
Out[24]: [[1, 2], [1, 2], [1, 2]]

但是,如果我按以下方式定义列表列表,它会起作用:

In [26]: a = [
   ....: [2,2],
   ....: [2,2],
   ....: [2,2],
   ....: ]

In [27]: a   
Out[27]: [[2, 2], [2, 2], [2, 2]]

In [28]: a[0][0]=1

In [29]: a
Out[29]: [[1, 2], [2, 2], [2, 2]]

对我来说,第 22 行和第 27 行看起来是一样的。那么有什么区别呢?

有人可以解释一下如何解决这个问题,特别是如何更改更改列表列表中单个项目的代码吗?如果这是不可能的,有什么建议可以转移到不同的数据结构吗?谢谢

4

1 回答 1

0

There is a fundamental difference in the 2 ways you defined the matrix in both code samples. In the first (line 21) when you multiply the outer list by 3 you actually multiply the references to the inner list.

Here's a parameterized example:

a = [2,2]
b = [a] * 3
b => [a, a, a] => [[2,2], [2,2], [2,2]]

As you can see the numerical representation of b is what you would expect, but it actually contains 3 references to a. So if you change either of the inner lists, they all change, because they are actually the same list.

Instead of multiplication you need to clone the lists doing something like this

new_list = old_list[:]

or

new_list = list(old_list)

In the case of nested lists, this can be done using loops.

于 2012-09-02T15:58:00.560 回答