通过迭代创建列表列表-不理解为什么variable.append()多次给我相同的列表,而不是每个列表都是唯一的.<



我想创建一个列表的列表,每个子列表增加1。

换句话说

[[1],
[1, 2],
[1, 2, 3],
[1, 2, 3, 4],
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5, 6],
[1, 2, 3, 4, 5, 6, 7],
[1, 2, 3, 4, 5, 6, 7, 8],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]

我写了下面的代码,但我不明白为什么list_of_lists在一行中返回相同的东西10次。

我已经找到了如何正确执行的示例,但我想理解为什么下面的代码将相同版本的临时列表附加到list_of_lists,而不是每个新版本附加一次。

list_of_lists = []
temporary = []
for i in range(1,11):
temporary.append(i)
print(temporary)
# the temporary list iterates as expected when I print it. When i is 1, it prints [1]. When i is 2, it  prints [1,2]
list_of_lists.append(temporary)
print(list_of_lists)
# "list of lists" simply appends the LATEST version of "temporary" list i number of times.

我的理由是list_of_lists.append(temporary)应该简单地将1个版本的临时列表追加到末尾。我不明白为什么它会覆盖之前附加的临时列表版本,而不是简单地将最新的一个附加到list_of_lists

中已经存在的条目上我已经看到了如何正确地做到这一点的例子,所以这个问题在功能上解决了。但如果有人能花点时间解释一下为什么我的逻辑是错误的,我将不胜感激。

谢谢。

I was expected:

[[1],
[1, 2],
[1, 2, 3],
[1, 2, 3, 4],
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5, 6],
[1, 2, 3, 4, 5, 6, 7],
[1, 2, 3, 4, 5, 6, 7, 8],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]

我:

[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]

如果使用list_of_lists.append(temporary),则只添加引用到临时列表。这意味着当您打印list_of_lists时,它会检查查看临时列表的最新版本,并打印出来。因此,在temporary中所做的任何更改都会自动在list_of_lists中进行。

为了解决这个问题,您可以使用temporary.copy()来附加列表的副本,而不是附加临时列表。

试试这个:

list_of_lists = []
temporary = []
for i in range(1,11):
temporary.append(i)
print(temporary)
list_of_lists.append(temporary.copy()) #this should fix it
print(list_of_lists)

然后输出:

[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6, 7], [1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]

代替:

list_of_lists.append(temporary)

你可以这样写:

list_of_lists.append(temporary[:])

区别在于,第一行只向列表追加了一个引用,而第二行通过[:]创建了一个列表的副本。

相关内容

最新更新