python - 为什么调用另一个数组后我没有调用的数组发生变化?
问题描述
我目前对为什么我的一个数组在没有被调用时会发生变化感到困惑。
if 2 <= self.counter <= 3:
print(self.old[y][x])
self.grid[y][x] = 1
print(self.old[y][x])
第一次打印显示 0,第二次打印显示 1。我只是在更改新版本的网格,所以我很困惑为什么这个值会发生变化。在代码的前面(如下所示),我编写了self.old = self.grid
这样我可以更改 self.grid 中的值,同时仍然保留原始网格。
这是完整的代码:
# Rules
# Any live cell with 2/3 live cell survives
# Any dead cell with =3 live cells becomes a live cell
# All other cells die in the next generation.
# 0 - dead, 1 - alive
import os
from time import sleep
class Life:
def __init__(self):
self.grid = [[0, 0, 0, 0],
[0, 1, 0, 0],
[1, 1, 0, 0],
[0, 0, 0, 0]]
self.h = 3
self.w = 3
def check(self, y, x):
if (0 <= x <= self.w) and (0 <= y <= self.h):
if self.old[y][x] == 1:
print("Pass", x,y)
self.counter += 1
def display(self):
for item in self.grid:
print(item)
def display_old(self):
for item in self.old:
print(item)
def start(self):
for gen in range(0, 3):
os.system("cls")
print("Generation: ", gen)
self.display()
self.old = self.grid
for y in range(0, 4):
for x in range(0, 4):
#print(y, x)
print("\n")
self.display_old()
self.counter = 0
# Checking neighbours
self.check(y - 1, x - 1) # Up/Left
self.check(y - 1, x) # Up
self.check(y - 1, x + 1) # Up/Right
self.check(y, x - 1) # Left
self.check(y, x + 1) # Right
self.check(y + 1, x - 1) # Down/Left
self.check(y+1, x) # Down
self.check(y+1, x+1) # Down/Right
print(f"Neighbours around grid[{y}][{x}]:", self.counter)
# Rules
if 2 <= self.counter <= 3:
print(self.old[y][x])
self.grid[y][x] = 1
print(self.old[y][x])
else:
self.grid[y][x] = 0
self.display()
sleep(1)
l = Life()
l.start()
解决方案
推荐阅读
- ios - 如何使用委托方法从捕获会话中提取视频?
- python - Itertools 循环方法——为什么是“while”循环?
- python - 没有出现在 Tensorflow-PyCharm IDE 中的可视化
- excel - VBA 或 Excel 函数计算逗号分隔字符串中的非零
- python - Raspberry Pi Google Assistant 上的 Google 自定义设备操作给出错误
- python - ATM SCRIPT CODIO - 试图理解我的错误。任何见解将不胜感激
- python - 使用逗号分隔的输入检查嵌套列表
- stanford-nlp - 向量空间模型 - 计算出查询向量 [0, 0.707, 0.707]
- javascript - spyOn 静态方法 - Jasmine ES6
- javascript - 无法在前端访问烧瓶 @login-required API