0

Given a list like this:

grid = [['R', 'S', 'S', 'I', 'Q', 'A', 'S', 'T', 'K'],
        ['Q', 'O', 'E', 'A', 'I', 'E', 'S', 'T', 'A'],
        ['D', 'B', 'M', 'X', 'F', 'E', 'O', 'K', 'I']]

I could access the 1st row, 3rd column like this:

print(grid[1][3])

But what I actually like to do is iterate through the values in the grid and obtain their rowth and columnth value. I tried with my knowledge and here is my code:

word = "A"
items = []
for rows in grid:
    for column in rows:
        if word == column:
            items.append([grid.index(match),  match.index(string)])

But while I print it : [[0, 5], [1, 3], [1, 3]]. Instead of getting [1, 8] in third place, I get the value of before matrix repeated. I tried many times but I failed. Please help me.

Thank you.

1 Answers1

0

You can use enumerate to keep track of the x and y coords of the element you are currently looking at, rather than having to call index (which is why you are finding the same element twice).

for x, rows in enumerate(grid):
    for y, column in enumerate(rows):
        if word == column:
            items.append([x, y])

This prints: [[0, 5], [1, 3], [1, 8]]

Loocid
  • 6,112
  • 1
  • 24
  • 42