我无法在python中复制列表

时间:2018-04-17 19:20:38

标签: python list copy

我试图创建一个列表副本并在我的函数中使用它。

import copy
islands=[['a','b','c',],[]]
def transfer(thing):
    new_islands=copy.copy(islands)
    new_islands[0].remove(thing)
    return new_islands
transfer('b')
print(islands)
//output ['a','c']

我尝试过其他复制方法,例如new_list=old_list[:],甚至创建一个for循环,将每个元素追加到一个空列表中,但我仍然无法将两个列表分开。

很抱歉,如果之前有人询问,但我真的无法找到问题的答案。

2 个答案:

答案 0 :(得分:1)

您还需要复制内部列表:

islands = [['a','b','c',],[]]

def transfer(thing):  
    new_islands = [islands[0].copy(), islands[1].copy()]
    new_islands[0].remove(thing)
    return new_islands

print(transfer('b'), islands)  # [['a', 'c'], []] [['a', 'b', 'c'], []]

您还可以使用deepcopy复制列表中的所有内容:

from copy import deepcopy

islands = [['a','b','c',],[]]
def transfer(thing):
    new_islands = deepcopy(islands)
    new_islands[0].remove(thing)
    return new_islands

答案 1 :(得分:-1)

让我们尝试简化并避免复制:

islands=[['a','b','c',],[]]
def transfer(islands, thing):
    return islands[0].remove(thing)

transfer(islands, 'b')
print(islands)
//output ['a','c']