所以我有一个astar算法在迷宫上输出路径。但我只想要在迷宫中实际转弯的节点(表示为元组(行,列))。
实施例。
path = [(10,0),(10,1),(9,1),(8,1),(8,2),(8,3),(7,3)] #given from astar alg
path = [(10,0),(10,1),(8,1),(8,3),(7,3)] #desired output
以下是我的代码的一部分:
for node in self.path:
direction1 = (self.path[node][0] - self.path[node+1][0], self.path[node][1] - self.path[node+1][1])
direction2 = (self.path[node+1][0] - self.path[node+2][0], self.path[node+1][1] - self.path[node+2][1])
if direction1 == direction2:
self.path.pop([node+1])
elif direction1 == None:
pass
else:
pass
答案 0 :(得分:0)
迭代self.path
使用的索引:
for node in range(len(self.path)):
但是由于你想在结束前停止检查2(以便self.path[node+2]
始终有效),只需使用:
for node in range(0,len(self.path)-2):
无论哪种方式,在迭代它时删除路径的元素都可能会导致问题,所以我建议构建新路径然后替换旧路径:
new_path = [self.path[0]] #keep the first element since it will always be needed
for node in range(0,len(self.path)-2):
direction1 = (self.path[node][0] - self.path[node+1][0], self.path[node][1] - self.path[node+1][1])
direction2 = (self.path[node+1][0] - self.path[node+2][0], self.path[node+1][1] - self.path[node+2][1])
if direction1 != direction2:
new_path.append(self.path[node+1])
new_path.append(self.path[-1]) #add in the last element
self.path = new_path
但这可能更令人困惑,因为你必须处理node+1
多node
所以你可能想从indice 1开始到len(self.path)-1
结束所以你会使用:< / p>
new_path = [self.path[0]] #keep the first element since it will always be needed
for node in range(1,len(self.path)-1):
direction1 = (self.path[node-1][0] - self.path[node][0], self.path[node-1][1] - self.path[node][1])
direction2 = (self.path[node][0] - self.path[node+1][0], self.path[node][1] - self.path[node+1][1])
if direction1 != direction2:
new_path.append(self.path[node])
new_path.append(self.path[-1]) #add in the last element
self.path = new_path