Skip to main content
 首页 » 编程设计

python之如何停止 Python 修改多个变量

2025年05月04日11lovecherry

当我尝试修改列表中的值时,它也在修改另一个列表中的单独值。我不认为这会是一个错误,但我想知道如何独立处理这些变量。

我已经对单个变量而不是列表进行了尝试,但没有出现这个问题。我可以单独设置列表,但是当有大量列表时,这似乎没有必要。

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]
列表_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]

两个列表都已修改

请您参考如下方法:

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?