返回列表的所有“位置”

时间:2011-01-18 02:22:32

标签: python list dictionary graph logic

我有一个带有“a”和“b”的列表,而“b”有点像路径而“a”是墙。我正在编写一个程序来绘制所有可能的动作。我运行代码来检查第一个“b”是否有可能的移动,但我不知道如何找到所有“b”,更不用重复检查它们。

我遇到的主要问题是将“b”的元组坐标从列表中删除。

任何指针/提示?

3 个答案:

答案 0 :(得分:2)

grid = [['b','a','b'],['b','b','b'],['a','a','a']
results = []
for row in range(len(grid)):
  for col in range(len(grid[row])):
    if grid[row][col] == 'b':
      results.append((row, col))

print results

使用地图可能有一些更好的方法,但自从我使用Python以来已经有一段时间了。

答案 1 :(得分:1)

+1给Nemo157答案。如果你想要完全相同的代码,但是在一行中,可以按如下方式完成:

grid = [['b','a','b'],['b','b','b'],['a','a','a']
[(row, col) for row in range(len(grid)) for col in range(len(grid[row])) if grid[row][col] == 'b']

干杯!

答案 2 :(得分:0)

这会找到每个方格的有效移动列表。

我假设在地图的边缘是一个“墙”,你不能对角移动:

# reference like this: maze[y][x] or maze[row][col]
# with [0][0] starting at the top left
maze = [['b','a','a', 'a'],
        ['b','a','b', 'a'],
        ['b','a','b', 'b'],
        ['b','b','b', 'a'],
        ['b','a','b', 'a'],
        ['a','a','a', 'a']]

moves = {}

# Loop through all cells of the maze, starting in the top-left
for y, row in enumerate(maze):
    for x, value in enumerate(row):
#        print "y, x, val: ", y, x, value
        # for every cell, create an empty list of moves
        moves[y, x] = []
        # then if we can move from this cell
        # check each of its neighbours and if they are a 'b' add it 
        # to the list of moves - assumes we can't move diagonally
        if value == 'b':
            if y - 1 > 0 and maze[y - 1][x] == 'b':
                moves[y, x].append((y - 1, x))
            if y + 1 < len(maze) and maze[y + 1][x] == 'b':
                moves[y, x].append((y + 1, x))
            if x - 1 > 0 and maze[y][x - 1] == 'b':
                moves[y, x].append((y, x - 1))
            if x + 1 < len(row) and maze[y][x+1] == 'b':
                moves[y, x].append((y, x+1))

print moves