【问题标题】:How to prevent value change in python [duplicate]如何防止python中的值变化[重复]
【发布时间】:2015-09-01 07:28:17
【问题描述】:

例如:

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

我改变了状态,但没有改变 current_state。 python中如何保持current_state值等于(5,[1,2,3])而不是去掉3?

谢谢!

【问题讨论】:

  • 另一个选项here.

标签: python


【解决方案1】:

一个选项是deepcopystate,所以它和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])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-15
    • 1970-01-01
    • 2020-03-07
    • 1970-01-01
    • 2017-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多