Python copy list issue
本问题已经有最佳答案,请猛点这里访问。
我不知道这里出了什么问题,不过我相信这里有人能帮忙。我有一个列表
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | def printer(lst): print"--------------" for x in lst: print x print"-------------- " def foo(lst, string): for x in lst: x[0] = string print"in foo" for x in lst: print x print"in foo " return lst mylst = [[1, 2, 3], [4, 5, 6]] print"mylst", id(mylst)," " 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 |
这是我电脑上的打印件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | 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] -------------- |
特别地:
1 | first = foo(copy.deepcopy(mylst),"first") |
你没有复制我的名单。两次调用foo时,都传递相同的对象引用并修改相同的列表。