Python: list of lists

前端 未结 7 1108
夕颜
夕颜 2020-11-27 04:38

Running the code

listoflists = []
list = []
for i in range(0,10):
    list.append(i)
    if len(list)>3:
        list.remove(list[0])
        listoflists.         


        
7条回答
  •  一向
    一向 (楼主)
    2020-11-27 05:19

    The list variable (which I would recommend to rename to something more sensible) is a reference to a list object, which can be changed.

    On the line

    listoflists.append((list, list[0]))
    

    You actually are only adding a reference to the object reference by the list variable. You've got multiple possibilities to create a copy of the list, so listoflists contains the values as you seem to expect:

    Use the copy library

    import copy
    listoflists.append((copy.copy(list), list[0]))
    

    use the slice notation

    listoflists.append((list[:], list[0]))
    

提交回复
热议问题