Python副本列表问题

Jef*_*eff 4 python

我不知道这里有什么问题,我相信这里有人可以提供帮助.我有一个列表mylst(列表列表)被复制并传递给方法foo. foo遍历列表并用传入的var替换行中的第一个元素并返回更改的列表.我打印清单,我看到它给了我期待的东西.我再次使用mylstvar的另一个副本和另一个副本重复该过程.所以两个返回的列表应该是不同的; 然而,当我再次检查第一个列表时,我看到它现在是第二个列表,也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
Run Code Online (Sandbox Code Playgroud)

这是在我的电脑上打印出来的

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]
--------------
Run Code Online (Sandbox Code Playgroud)

Gre*_*ill 7

这个lst[:]技巧可以复制一个级别的列表.您有嵌套列表,因此您可能希望查看copy标准模块提供的服务.

特别是:

first = foo(copy.deepcopy(mylst), "first")
Run Code Online (Sandbox Code Playgroud)