首页 > 解决方案 > 为什么调用另一个数组后我没有调用的数组发生变化?

问题描述

我目前对为什么我的一个数组在没有被调用时会发生变化感到困惑。

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()

标签: pythonarraysclassselfpython-3.8

解决方案


推荐阅读