我试图创建简单的字段表,用于存储有关其邻居的信息。这是我的代码:
class Field:
posx = 0
posy = 0
used = False
letter = ''
neighbours = []
def __init__(self, x, y):
self.posx = x
self.posy = y
def addNeighbour(self,neighbour):
self.neighbours.append(neighbour)
m, n = 2, 2 # size of table
fields=[[0 for y in range(0, n)] for x in range(0, m)]
for i in range(0, m):
for j in range(0, n):
fields[i][j] = Field(i, j)
for i in range(0, m):
for j in range(0, n):
for k in range(i-1, i+2):
for l in range(j-1, j+2):
if (k in range(0, m) and l in range(0, n)
and (k != i or l != j)):
print('{} {}'.format(i, j))
fields[i][j].addNeighbour(fields[k][l])
它打印出好的值,对于简单的2x2表,每个字段(i,j)有3个邻居。问题是,不是为每个字段分配3个邻居,而是将所有字段的邻居分配给所有字段(因此每个字段的邻居列表具有12个元素而不是3个)。任何人都可以指出我的代码有什么问题吗?
答案 0 :(得分:1)
let MyClass = require("myclass.js").MyClass;
是一个类变量,因此所有neighbours
实例都添加到同一个列表中。只需将其设为实例变量:
Field
此外,单一理解将用于创建字段网格:
class Field:
# do NOT put neighbours, posx, posy, letter here!! They are instance variables
def __init__(self, x, y):
self.posx = x
self.posy = y
self.neighbours = []
self.letter = ''