追加到for循环中的列表清单

问题描述:

我目前正在遍历列表的一个值.在每次迭代中,我都会将该列表追加到一个新列表中,以便获得一个列表列表.但是,我收到的输出不是我期望的.

I am currently iterating through one value of a list. On each iteration, I append the list to a new list, in order to have a list of lists. However, the outputs that I am receiving aren't what I am expecting them to be.

我已尽可能简化了问题,并得出了以下结论:

I've simplified the problem as much as possible and have arrived at this :

def Function():
     ListOfLists = []
     Lists = [0]
     for j in range(0, 5):
         Lists[0] = Lists[0] + 1
         print(Lists)
         ListOfLists.append(Lists)
     print("ListofLists:")
     print(ListOfLists)

Function()

输出给了我这个:

[1]
[2]
[3]
[4]
[5]
ListofLists:
[[5], [5], [5], [5], [5]]

我希望输出为:

[1]
[2]
[3]
[4]
[5]
ListofLists:
[[1], [2], [3], [4], [5]]

我要去哪里错了?谢谢

您必须附加列表的副本.当您说 List 时,它是参考.当 List 更改时, ListOfLists 也会更改.复制后可以防止这种所谓的(意外)行为.

You have to append a copy of list. When you say List, it's a reference. When List changes, ListOfLists changes. Making a copy prevents this so-called (un)expected behaviour.

替换此行代码:

ListOfLists.append(Lists)

具有:

ListOfLists.append(Lists[:])