0

I'm trying to get a list of indexes for a grid where the element is != 0 (the last part is not relevant to question however I thought I would add it)

#creating the grid
grid = [[0 for x in range(4)] for y in range(5)]
#taking each elements index 
grid = [[[x,y] for x, Cell in enumerate(Row) if Cell == 0 ] for y, Row in enumerate(grid)]

print grid #indexes
[[(0, 0), (1, 0), (2, 0), (3, 0)], [(0, 1), (1, 1), (2, 1), (3, 1)], [(0, 2), (1, 2), (2, 2), (3, 2)], [(0, 3), (1, 3), (2, 3), (3, 3)], [(0, 4), (1, 4), (2, 4), (3, 4)]]

I now need to select a random index. I'm planning on using random.choice(), however because it's a list of lists this will be problematic. I realize I could just do two random.choice()s but i'd rather understand list comprehensions better.

Thanks

EDIT:

I was able to do it without a LC:

index = []
for y, Row in enumerate(grid):
    for x, Cell in enumerate(Row):
        if self.grid[y][x] == 0:
            index.append((x,y))
David Hancock
  • 1,063
  • 4
  • 16
  • 28

1 Answers1

1

Here you are:

In[21]: [(x,y) for x in range(4) for y in range(5)]
Out[21]: 
[(0, 0),
 (0, 1),
 (0, 2),
 (0, 3),
 (0, 4),
 (1, 0),...

Just take rid of the list inside your comprehension to build all the indexes.

EDIT: Get rid on your code of the intermediate lists created

grid = [(x,y) for x, Cell in enumerate(Row) if Cell == 0 for y, Row in enumerate(grid)]

This should work.

Netwave
  • 40,134
  • 6
  • 50
  • 93
  • Hi thanks for the reply. This works, however in my actual code the grid is already created. I must take the grid and create of list of indexes for all elements with value 0. – David Hancock May 05 '16 at 08:35
  • @DavidHancock, do the same in your code, I cant really test it coz i dont have `Cell` or `Row` – Netwave May 05 '16 at 08:41
  • `Row` are the elements from iterating (or enumerating in my case) over `grid`, similarly `Cell` is the elements within `Row` – David Hancock May 05 '16 at 09:11