简体   繁体   English

如何在python中操作列表

[英]how to manipulate a list in python

I just wanting to ask you about an excercise in school based on construction of a maze in python. 我只是想问你一个关于用Python构建迷宫的运动知识。 We start with a known (x,y) point and the n*n graph. 我们从一个已知的(x,y)点和n * n图开始。 In each recursion we should make a neighbouring_list for every couple (x,y) which will contain the nearest elements of the point. 在每次递归中,我们应该为每对夫妇(x,y)制作一个neighbouring_list,其中将包含该点的最近元素。 So far I have written this code which shows correct results but I cannot save and manipulate exclusive the new x and y which are chosen from the neighbouring list. 到目前为止,我已经编写了这段显示正确结果的代码,但是我无法保存和操作从相邻列表中选择的新x和y的排他性。 They perform in a way like (8,8) and i can't manage to write x = 8 and y = 8. Have you got any idea? 它们的执行方式类似于(8,8),我无法写出x = 8和y = 8。 Thank you in advance! 先感谢您!

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

Here's a much simpler version of your code: 这是您的代码的简单得多的版本:

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

That should be a lot easier to manage. 这应该更容易管理。

To unpack a tuple (xin, yin) into x, y for your code, you can simply do this: 要将元组(xin,yin)解压缩为代码的x,y,只需执行以下操作:

x, y = (xin, yin)

or if the tuple is bound to a variable, say, coordinates: 或者如果元组绑定到变量,例如坐标:

x, y = coordinates

This is known as tuple unpacking. 这称为元组拆包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM