我在python中将一个列表复制到另一个列表。之后我在第二个列表中进行了更改

时间:2018-02-13 11:40:27

标签: python

x = [[7, 8], 3, "hello", [6, 8], "world", 17] # List 1
w = list.copy(x) # copying list 1 to list 2
w[0][1] = 5 # changing the value in list 2
print(w)
print(x)

输出:

[[7, 5], 3, 'hello', [6, 8], 'world', 17]
[[7, 5], 3, 'hello', [6, 8], 'world', 17]

w的更改也会影响x

3 个答案:

答案 0 :(得分:1)

from copy import deepcopy
x = [[7, 8], 3, "hello", [6, 8], "world", 17]
w = deepcopy(x)

w[0][1] = 5 # changing the value in list 2
print(w)
print(x)

结果:

[[7, 5], 3, 'hello', [6, 8], 'world', 17]
[[7, 8], 3, 'hello', [6, 8], 'world', 17]

答案 1 :(得分:0)

您需要使用copy.deepcopy(),因为copy.copy()仅复制列表中元素的引用。

答案 2 :(得分:0)

vect.end()是您问题的答案:

deepcopy