如何在Python中防止值的改变

2024-09-24 06:24:34 发布

您现在位置:Python中文网/ 问答频道 /正文

例如:

>>> state = (5,[1,2,3])
>>> current_state = state
>>> state[1].remove(3)
>>> state
(5, [1, 2])
>>> current_state
(5, [1, 2])

我改变了状态,但不是现在的状态。如何保持当前的状态值等于(5,[1,2,3]),而不是在python中删除3?你知道吗

谢谢!你知道吗


Tags: 状态currentremovestate状态值
1条回答
网友
1楼 · 发布于 2024-09-24 06:24:34

一个选项是^{}state,因此它和current_state引用不同的对象:

>>> from copy import deepcopy
>>> state = (5,[1,2,3])
>>> current_state = deepcopy(state)
>>> state[1].remove(3)
>>> state
(5, [1, 2])
>>> current_state
(5, [1, 2, 3])

相关问题 更多 >