Yesterday I worked on a game where I had to cross a two-dimensional array and find the location of any cells marked "d" (where the cells are represented as "-" for empty or "d" for dirty).
I did this using two for-loops:
def find_dirty_cells(board): dirty_cells = [] for enum, row in enumerate(board): for enumrow, cell in enumerate(row): if cell == 'd': dirty_cells.append((enum, enumrow)) return dirty_cells
But then I thought it was better to build a generator object and return it instead, so I wrote the following:
def find_dirty_cells(board): return ((enum, enumrow) for enumrow, cell in enumerate(row) for enum, row in enumerate(board) if cell == 'd')
But the second gives me the wrong data in response (that is, it does not find the cell "d"). There must be something simple, I miss, which makes the second not equal to the first, but I do not see it. The real question I was trying to solve is this: is there an easy way to make my first attempt to return the generator?
source share