In python why is a list not the same as list[:]?
本问题已经有最佳答案,请猛点这里访问。
我有一个列表,
1 | print(ls is ls[:]) |
我得到的输出是
1 2 3 4 5 6 | >>> ls = [0, 1, 2, 3, 4] >>> new_ls = ls[:] >>> id(ls) == id(new_ls) False >>> id(ls[0]) == id(new_ls[0]) True |
这基本上是
python中的字符串比较:is与==
你只是不知道而已。
因此
1 2 3 4 5 | a == a[:] >> True a is a[:] >> False |
1 2 3 4 5 6 7 8 9 | >>> a = [1,2] >>> b = a >>> id(a) 140177107790232 >>> id(b) 140177107790232 >>> b.remove(1) >>> a [2] |
但是如果你用切片的方法来做的话:
1 2 3 4 5 6 7 8 9 10 | >>> a = [1,2] >>> b = a[:] >>> id(a) 140177107873232 >>> id(b) 140177107873304 >>> b.remove(1) >>> a [1, 2] >>> |
例子:
1 2 3 4 5 6 7 8 9 | s = [5, 6, 2, 4] =>s [5, 6, 2, 4] new_s = s new_s.append(100) =>new_s [5, 6, 2, 4, 100] =>s [5, 6, 2, 4, 100] |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | s = [5, 6, [5, 6, 2, 4], 4] new_s = s[:] new_s[2].append(45) =>s [5, 6, [5, 6, 2, 4, 45], 4] #both sublists are still being referenced =>new_s [5, 6, [5, 6, 2, 4, 45], 4] import copy s1 = [5, 6, [5, 6, 2, 4], 4] new_s1 = copy.deepcopy(s1) new_s1[2].append(100) =>new_s1 [5, 6, [5, 6, 2, 4, 100], 4] =>s1 [5, 6, [5, 6, 2, 4], 4] |