代码之家  ›  专栏  ›  技术社区  ›  dsdsds sdsds

.pop()从原始列表中删除元素[重复]

  •  1
  • dsdsds sdsds  · 技术社区  · 2 年前

    在创建智力竞赛游戏时,我在使用时遇到了一个奇怪的发现。方法在作为另一个列表副本的列表上,原始列表的项将被删除。 我编写了这个简单的代码,让您更好地理解我的意思:

    myList = [1, 2, 3, 4]
    myListDup = myList
    print("{}\n{}".format(myListDup, myList))
    
    for i in range(len(myList)):
        myListDup.pop()
    
    print("{}\n{}".format(myListDup, myList))
    

    如图所示,使用后。pop()要从myListDup中删除所有元素,myList也是空的(我知道还有其他方法可以删除元素,但我需要在我的原始程序中使用.pop()) 有没有办法避免这种情况?

    3 回复  |  直到 2 年前
        1
  •  2
  •   SigKill    2 年前

    当你在做 myListDup = myList 这只是创建另一个引用 myListDup 到原始列表 myList .

    尝试以下操作:

    myListDup = list(myList)
    

    myListDup = myList[:]
    
    

    这将创建列表的新副本,然后将其分配给 myListDup

        2
  •  0
  •   QuantumX    2 年前

    使用 copy() ,

    myList = [1, 2, 3, 4]
    myListDup = myList.copy()
    print("{}\n{}".format(myListDup, myList))
    
    for i in range(len(myList)):
        myListDup.pop()
    
    print("{}\n{}".format(myListDup, myList))
    
        3
  •  0
  •   Sourin Karmakar    2 年前

    您可以使用列表 copy 复制列表的方法

    喜欢

    mylist = [1, 2, 3, 4]
    copy_list = my_list.copy()
    my_list.pop()
    print(my_list)
    print(copy_list)
    

    输出

    [1,2,3]
    [1,2,3,4]