且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

更改列表列表中的项目

更新时间:2023-01-01 08:02:57

在两个代码样本中定义矩阵的2种方式都有根本的不同.在第一行(第21行)中,将外部列表乘以3,实际上是将引用乘以内部列表.

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]]

如您所见,b的数字表示形式是您所期望的,但实际上它包含3个对a的引用.因此,如果您更改任何一个内部列表,它们都将更改,因为它们实际上是相同的列表.

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[:]

new_list = list(old_list)

对于嵌套列表,可以使用循环来完成.

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