Skip to main content
 首页 » 编程设计

python之尽管每个循环只分配一次变量,但为什么变量会发生变化

2025年05月04日29yjmyzz

我正在研究康威生命游戏的简单版本。当我输入诸如 0001 之类的内容时,输出应该是 1010。程序将 1 和 0 作为 bool 值处理。

在下面的代码片段中,我打印了“copy”变量,该变量每一代应该只改变一次。相反,每次 for 循环循环时它都在改变。为什么“副本”会发生变化? “状态”不应该是唯一改变的东西吗?

def adj(state,i): 
    a = b = False 
    if i == 0: #checking on left wall 
        a = state[-1] 
        b = state[i+1] 
    elif i == len(state)-1: #checking on right wall 
        a = state[i-1] 
        b = state[0] 
    else: #checking in the middle 
        a = state[i-1] 
        b = state[i+1] 
    return [a,b].count(True) 
 
def evolve(state): 
    copy = state #changes are made to state based on the copy 
    for i in range(len(copy)): 
        print(copy) 
        if adj(copy,i) == 1: 
            state[i] = True 
        else: 
            state[i] = False 
    return state 

请您参考如下方法:

这行代码:

copy = state 

不制作“状态”的单独副本。 “copy”和“state”现在指的是同一个列表对象。

如果您想要一个单独的副本,请改用切片:

copy = state[:]