【问题标题】:Python copy list issue [duplicate]Python复制列表问题[重复]
【发布时间】:2012-01-11 03:40:33
【问题描述】:

我不知道这里出了什么问题,但我相信这里有人可以提供帮助。我有一个列表mylst(列表列表),它被复制并传递给方法foofoo 遍历列表并将行中的第一个元素替换为传入的 var 并返回更改后的列表。我打印了这份清单,我发现它给了我我的期望。我再次使用mylst 的另一个副本和另一个传入的var 重复该过程。所以两个返回的列表应该是不同的;但是,当我再次检查第一个列表时,我发现它现在是第二个列表,mylst 也已更改为第二个列表。我没有正确复制列表吗?我用mylst[:] 方法复制它。另一个有趣的观察是所有列表 ID 都是不同的。这是否意味着它与其他列表不同?这是我的问题的一个例子。

def printer(lst):
    print "--------------"
    for x in lst:
        print x
    print "--------------\n"

def foo(lst, string):

    for x in lst:
        x[0] = string

    print "in foo"
    for x in lst:
        print x
    print "in foo\n"

    return lst

mylst = [[1, 2, 3], [4, 5, 6]]
print "mylst", id(mylst), "\n"

first = foo(mylst[:], "first")
print "first", id(first)
printer(first) # Correct

second = foo(mylst[:], "second")
print "second", id(second)
printer(second) # Correct

print "first", id(first)
printer(first) # Wrong

print "mylst", id(mylst)
printer(mylst) # Wrong

这是我电脑上的打印输出

mylst 3076930092 

in foo
['first', 2, 3]
['first', 5, 6]
in foo

first 3076930060
--------------
['first', 2, 3]
['first', 5, 6]
--------------

in foo
['second', 2, 3]
['second', 5, 6]
in foo

second 3076929996
--------------
['second', 2, 3]
['second', 5, 6]
--------------

first 3076930060
--------------
['second', 2, 3]
['second', 5, 6]
--------------

mylst 3076930092
--------------
['second', 2, 3]
['second', 5, 6]
--------------

【问题讨论】:

    标签: python


    【解决方案1】:

    lst[:] 技巧会复制 one 级列表。你有嵌套列表,所以你可能想看看copy标准模块提供的服务。

    特别是:

    first = foo(copy.deepcopy(mylst), "first")
    

    【讨论】:

    • 你知道为什么ID不同吗?
    • first列表的ID不同,但是你会发现包含在第一个列表的ID是一样的.
    • deepcopy 总是很神奇,我在这些场景中几乎盲目地使用它
    【解决方案2】:

    您没有制作另一个 mylist 副本。两次调用 foo 时,都传递了相同的对象引用并修改了相同的列表。

    【讨论】: