如何将路径的(X,Y)坐标列表分成X和Y坐标的单独列表?

时间:2015-03-04 16:10:27

标签: python python-2.7 split coordinates instance

在以下功能中,' graph'是一个二维网格列表,由一个零,一个零和一个'两个'组成。 (分别为障碍物,空旷地区和目标),开始'是开始搜索的重点。

def bfs(graph,start):

fringe = [[start]]
# Special case: start == goal
if start.val == 'g':
    return [start]
start.visited = True
# Calculate width and height dynamically. We assume that "graph" is dense.
width = len(graph[0])
height = len(graph)
# List of possible moves: up, down, left, right.

moves = [(-1, 0), (1, 0), (0, -1), (0, 1)]
while fringe:
    # Get first path from fringe and extend it by possible moves.

    path = fringe.pop(0)
    #print path
    node = path[-1]
    pos = node.pos
    # Using moves list (without all those if's with +1, -1 etc.) has huge benefit:
    # moving logic is not duplicated. It will save you from many silly errors.

    for move in moves:
        # Check out of bounds. Note that it's the ONLY place where we check it.
        if not (0 <= pos[0] + move[0] < height and 0 <= pos[1] + move[1] < width):
            continue
        neighbor = graph[pos[0] + move[0]][pos[1] + move[1]]
        if neighbor.val == 'g':
            return path + [neighbor]
        elif neighbor.val == 'o' and not neighbor.visited:
            neighbor.visited = True
            fringe.append(path + [neighbor])  # creates copy of list
raise Exception('Path not found!')

TRANSLATE = {0: 'o', 1: 'x', 2: 'g'}
graph = [[Node(TRANSLATE[x], (i, j)) for j, x in enumerate(row)] for i, row in enumerate(graph)]
# Find path
path = bfs(graph, graph[4][4])

当我打印路径的值时,我得到以下内容:

  
    
      

路径        [(4,4),(4,5),(4,6),(4,7),(4,8),(3,8),(2,8),(1,8),( 1,9)]

    
  

这些是x和y坐标。

现在我如何将坐标作为单独的列表来获取&#39; x&#39;并且&#39; y&#39;坐标?

我的首选输出是

X_list=[4,4,4,4,4,3,2,1,1]
Y_list=[4,5,6,7,8,8,8,8,9]

P.S:当我检查&#34;类型&#34;在打印的路径中,它将其显示为“实例”。

请帮助我,因为我在经过大量搜索后陷入困境,以达到我的首选输出。

我请你在这方面给我启发。非常感谢!!

2 个答案:

答案 0 :(得分:4)

你可以使用列表理解。

>>> l = [(4, 4), (4, 5), (4, 6), (4, 7), (4, 8), (3, 8), (2, 8), (1, 8), (1, 9)]
>>> la = [x for x,y in l]
>>> lb = [y for x,y in l]
>>> la
[4, 4, 4, 4, 4, 3, 2, 1, 1]
>>> lb
[4, 5, 6, 7, 8, 8, 8, 8, 9]

答案 1 :(得分:0)

您可以将元组转置并映射到列表或使用map和itemgetter。

from operator import itemgetter
l = [(4, 4), (4, 5), (4, 6), (4, 7), (4, 8), (3, 8), (2, 8), (1, 8), (1, 9)]

a,b = map(itemgetter(0),l), map(itemgetter(1),l)
print(a,b)

a,b = map(list,zip(*l))

print(a,b)
[4, 4, 4, 4, 4, 3, 2, 1, 1] [4, 5, 6, 7, 8, 8, 8, 8, 9]
[4, 4, 4, 4, 4, 3, 2, 1, 1] [4, 5, 6, 7, 8, 8, 8, 8, 9]

您需要在班级中添加iter,以便迭代对象:

 def __iter__(self):
        return iter(self.coords)

class Node():
    def __init__(self, pos):
        self.pos = pos

    def __iter__(self):
        return iter(self.pos)

l = []
for x in [(1, 5), (2, 6), (3, 7), (4, 8)]:
    l.append(Node(x))


print("{}".format(list(map(list,zip(*l)))))

[[1, 2, 3, 4], [5, 6, 7, 8]]

使用Queuebfs将是一种有效的解决方案: