这项工作是为了一项任务。我正在使用2d数组,到目前为止,我找到了一个我想要通过数组的路径。数组中还有其他路径,我希望能够通过它们,但我不能重用任何路径。我的数组看起来像:
0,2,4,1,6,0,0
2,0,0,0,5,0,0
4,0,0,0,5,5,0
1,0,0,0,1,1,0
6,5,0,1,0,5,5
0,0,5,1,5,0,0
0,0,0,0,5,0,0
我找到附近邻居的代码是:
def check_neighbours(Alist, node):
nodes = []
for i in range(0,2):
for j in range(0,2):
x = node[0]+i
y = node[1]+j
if x>=0 and y>=0 and (i!=0 or j!=0) and Alist[x][y]>0:
nodes.append([x, y])
我将每个访问过的坐标x,y附加到一个列表,该列表构建了所采用的完整路径。以下是输出的示例:
inside pathing function
path taken is ['[0, 1]', '[0, 2]', '[0, 3]', '[0, 4]', '[1, 4]', '[2, 4]', '[2, 5]', '[3, 5]', '[4, 5]', '[4, 6]']
由于我搜索邻居的方式(x和y分开),我想不出一种方法来测试构建的当前坐标是否已经位于列表内部。我认为代码适合以下两行:
if x>=0 and y>=0 and (i!=0 or j!=0) and Alist[x][y]>0:
nodes.append([x, y])
答案 0 :(得分:0)
怎么样?
nodes = []
nodes.append([1,1])
nodes.append([2,2])
nodes.append([3,3])
[1,1] in nodes
# True
[1,3] in nodes
# False
我对你的问题并不是很清楚,所以这可能是关闭的。
话虽如此,因为,为了添加到nodes
列表,它必须是前一节点的右列,下面一列或两者。由于您只考虑右侧和下方的节点(range(0,2)
),因此您的列表中永远不会出现重复。