当我尝试修改列表中的值时,它也在修改另一个列表中的单独值。我不相信这会是一个错误,但我想知道如何独立对待这些变量。
我已经针对单个变量而不是列表尝试了此操作,并且不会发生此问题。我可以分别设置列表,但是对于有大量列表的情况,这似乎是不必要的。
numbers = [1,2,3,4,5]
list_A = numbers
list_B = numbers
print("list A:",list_A)
print("list B:",list_B)
list_A[2] = 10
print("list A:",list_A)
print("list B:",list_B)
我期望输出为:
list_A:[1、2、3、4、5]
list_B:[1、2、3、4、5]
list_A:[1、2、10、4、5]
list_B:[1、2、3、4、5]
但是得到这个:
list_A:[1、2、3、4、5]
list_B:[1、2、3、4、5]
list_A:[1、2、10、4、5]
list_B:[1、2、10、4、5]
两个列表均已修改的地方
答案 0 :(得分:3)
numbers = [1,2,3,4,5]
list_A = numbers.copy()
list_B = numbers.copy()
print("list A:",list_A)
print("list B:",list_B)
list_A[2] = 10
print("list A:",list_A)
print("list B:",list_B)
这是python,所以您必须这样做。
有关更多信息,请参见How to clone or copy a list?
答案 1 :(得分:2)
就像您在这里所做的一样:
list_A = numbers
list_B = numbers
您正在复制整个对象,但是它将更改所有列表,因此您需要:
list_A = numbers.copy()
list_B = numbers.copy()
或者:
list_A = numbers[:]
list_B = numbers[:]
或者:
list_A = list(numbers)
list_B = list(numbers)
答案 2 :(得分:1)
使用newList = oldList
创建列表意味着两个列表是链接的,因为它们都是对同一列表的引用。使用newList = list(oldList)
创建一个新列表。
答案 3 :(得分:1)
看到这种情况的原因是因为Python默认情况下分配的是引用而不是结构的值。要实现所需的功能,您需要使用一种如上面回复中所示的复制方式。
如果您尝试打印变量,将会看到此信息
答案 4 :(得分:0)
您正在使用引用访问阵列。您有多种选择可以做到这一点。最简单的方法是通过迭代再次制作数组:
numbers = [1,2,3,4,5]
list_A = [i for i in numbers]
list_B = [i for i in numbers]
以此创建具有不同引用的数组。
您也可以阅读以下文档:https://docs.python.org/2/library/copy.html
您也可以尝试以下方法:
# shallow copy of array, means that it handles the simple copy but not the nested ones(if you have a `list` in `list`)
list_A = copy.copy(numbers)
list_B = copy.copy(numbers)
# deep copy of array, so handles nested ones too
list_A = copy.deepcopy(numbers)
list_B = copy.deepcopy(numbers)
在您的情况下,两者都可以工作