追加到for循环中的列表清单 [英] Appending to list of lists in for loop

查看:58
本文介绍了追加到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[:])

这篇关于追加到for循环中的列表清单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆