首页 > 解决方案 > list1 在我的代码中的任何地方都不会被分配等于 list2,但是 list1 的值仍然被复制到 list2

问题描述

我尝试使用一些打印语句来调试代码。所以,我在这里展示整个代码。

l = ['one', 'two', 'three',  'four', 'five']

l1 = list()
count = 0
l2 = list()

for r in range(len(l)):

    print(r, 'this is r')
    print()
    if count < 2:
   
        l1.append(l[r])
        print(l1)
        print(l2)  #when the loop runs for the third time l2 is automatically updating to l1, which 
                   #is now ['one','two,'three'].Why?
        
        count += 1
        
    if count == 2:
    
        l2.append(l1)
        print(l2, 'this is l2')
        print()
        count = 0
    
print(l2)         
    

我认为 l2 的输出应该是: [['one', 'two'], ['one', 'two', 'three', 'four']]

但我得到的输出是: [['one', 'two', 'three', 'four', 'five'], ['one', 'two', 'three', 'four', 'five ']]

标签: pythonlist

解决方案


推荐阅读