I Have a list with "a" and "b" and the "b"'s are somewhat of a path and "a"'s are walls. Im writing a program to make a graph of all the possible moves. I got the code running to check the first "b" for possible moves, but i ha开发者_运维知识库ve NO Idea how im going to find all "b"'s , even less check them all without repeating.
Major issue im having is getting the tuple coordinates of the "b"'s out of the list.
Any pointers/tips?
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
There's probably some better way of doing it using maps but its been awhile since I've used Python.
+1 to Nemo157 for his answer. If you want the exact same code, but in one line, it can be done as follows:
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']
Cheers!
This finds a list of valid moves from every square.
I am assume that off the edge of the map is a "wall", and that you can't move diagonally:
# 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
精彩评论