我只是想问你在学校里根据蟒蛇迷宫的构造进行锻炼。我们从已知的(x,y)点和n * n图开始。在每次递归中,我们应该为每对(x,y)创建一个neighbouring_list,它将包含该点的最近元素。 到目前为止,我已经编写了这段显示正确结果的代码,但是我无法保存和操作独占于从邻近列表中选择的新x和y。它们以(8,8)的方式执行,我无法写x = 8和y = 8.你有什么想法吗?提前谢谢!
if(x and y == 0):
neighbouring_list = [((x + 1), y), (x, (y + 1))]
elif (x == (n - 1) and y == 0):
neighbouring_list = [((x - 1), y), (x, (y + 1))]
elif (y == 0):
neighbouring_list = [((x + 1), y), ((x - 1), y), (x, (y + 1))]
elif (y == (n - 1) and x == 0):
neighbouring_list = [(x, (y - 1)), ((x + 1), y)]
elif (x == 0):
neighbouring_list = [(x, (y + 1)), (x, (y - 1)), ((x + 1), y)]
elif (x == (n - 1) and y == (n - 1)):
neighbouring_list = [(x, (y - 1)), ((x - 1), y)]
elif (x == (n - 1)):
neighbouring_list = [((x - 1), y), (x, (y + 1)), (x, (y - 1))]
elif (y == (n - 1)):
neighbouring_list = [(x, (y - 1)), ((x - 1), y), ((x + 1), y)]
else:
neighbouring_list = [((x - 1), y), ((x + 1), y), (x, (y + 1)), (x, (y - 1))]
答案 0 :(得分:2)
这是一个更简单的代码版本:
nlist = []
if x < n:
nlist.append((x+1,y))
if y < n:
nlist.append((x,y+1))
if x > 0:
nlist.append((x-1,y))
if y > 0:
nlist.append((x,y-1))
这应该更容易管理。
要将元组(xin,yin)解压缩为x,y代码,您只需执行以下操作:
x, y = (xin, yin)
或者如果元组绑定到变量,比如坐标:
x, y = coordinates
这称为元组解包。