简体   繁体   English

附加到 for 循环中的列表列表

[英]Appending to list of lists in for loop

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.在每次迭代中,我将 append 列表转换为一个新列表,以便获得一个列表列表。 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()

The output gives me this: output 给了我这个:

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

I would've expected the output to be:我本来希望 output 是:

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

Where am I going wrong?我哪里错了? Thanks谢谢

You have to append a copy of list.您必须为 append 列表的副本。 When you say List , it's a reference.当您说List时,它是一个参考。 When List changes, ListOfLists changes.List改变时, ListOfLists改变。 Making a copy prevents this so-called (un)expected behaviour.制作副本可防止这种所谓的(非)预期行为。

Replace this line of code:替换这行代码:

ListOfLists.append(Lists)

with:和:

ListOfLists.append(Lists[:])

That is because all appended instances are referring to the same address in memory.这是因为所有附加的实例都指向 memory 中的相同地址。

PROBLEM:问题:

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

SOLUTION:解决方案:

Check Check What is the difference between list and list[:] in python?检查 检查python 中的 list 和 list[:] 有什么区别? . .

Use [:] for creating a different object (shallow copy) in this case.在这种情况下,使用[:]创建不同的 object(浅拷贝)。 You read about deep copy and shallow copy in Python to understand more about how actually Python treats with references.您在 Python 中阅读了有关深拷贝浅拷贝的内容,以了解更多关于 Python 实际如何处理引用的信息。 For more details, check https://www.programiz.com/python-programming/shallow-deep-copy .有关更多详细信息,请查看https://www.programiz.com/python-programming/shallow-deep-copy

Replace ListOfLists.append(Lists) with ListOfLists.append(Lists[:]) .ListOfLists.append(Lists)替换为ListOfLists.append(Lists[:])

In [2]: 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:
[[1], [2], [3], [4], [5]]

In [3]:            

Try this:尝试这个:

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

When you append Lists to ListofLists , it does not make a separate copy the list and append it.当您将 append Lists复制到ListofLists时,它不会单独复制列表和 append 它。 Instead, it just appends a reference to the List list inside ListofLists .相反,它只是在ListofLists中附加了对List列表的引用。 This is often confusing as a beginner.作为初学者,这常常令人困惑。 If you mutate List next time, the value inside ListofLists will also change as both of them are referencing the same list.如果你下次改变ListListofLists中的值也会改变,因为它们都引用了同一个列表。 If you want to have a completely separate list every time, you should use copy() method on list or `Lists[:]'.如果你想每次都有一个完全独立的列表,你应该使用 list 或 `Lists[:]' 上的copy()方法。 Or you can create the list on the fly while appending, as follows:或者您可以在附加时动态创建列表,如下所示:

ListofLists = []
for number in range(1,6):
    print([number])
    ListofLists.append([number])
print(ListofLists)

And much more simple and readable way would be to use a list comprehension, like follows:更简单易读的方法是使用列表推导,如下所示:

ListofLists = [[number] for number in range(1, 6)]
print(ListofLists)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM