Obtain coordinates of an element in a two-dimensional array based on X and Y

1

I have the following list:

laberinto = [
    ['*', '*', '|', '|', '|', '|', '|', '|', '|', '|'],
    ['|', '*', '*', '*', '|', '|', '|', '|', '|', '|'],
    ['|', '|', '|', '*', '|', '|', '*', '*', '*', '|'],
    ['|', '|', '|', '*', '|', '|', '*', '|', '*', '|'],
    ['|', '|', '|', '*', '*', '*', '*', '|', '*', '*'],
    ['|', '|', '|', '|', '|', '|', '|', '|', '|', '*'],
    ['|', '|', '|', '|', '|', '|', '|', '*', '*', '*'],
    ['|', '|', '|', '|', '|', '|', '|', '*', '|', '|'],
    ['|', '|', '|', '|', '|', '|', '|', '*', '|', '|'],
    ['|', '|', '|', '|', '|', '|', '|', '*', '*', '*'],
]

I would like to obtain the X and Y coordinates of each of the *, I have been able to go through the whole matrix with 2 cycles for but I can not understand how to obtain their coordinates, I used and tried with the method index but only I get the X coordinate of a single element.

    
asked by KevinBueno_ 13.10.2017 в 00:52
source

1 answer

1

The problem with list.index is that only the first element that you find in your row will return you, which makes things difficult. Instead of index use a conditional of type if elemento == '*' .

A simple and efficient option is to use enumerate in compression of lists or generators.

laberinto = [
    ['*', '*', '|', '|', '|', '|', '|', '|', '|', '|'],
    ['|', '*', '*', '*', '|', '|', '|', '|', '|', '|'],
    ['|', '|', '|', '*', '|', '|', '*', '*', '*', '|'],
    ['|', '|', '|', '*', '|', '|', '*', '|', '*', '|'],
    ['|', '|', '|', '*', '*', '*', '*', '|', '*', '*'],
    ['|', '|', '|', '|', '|', '|', '|', '|', '|', '*'],
    ['|', '|', '|', '|', '|', '|', '|', '*', '*', '*'],
    ['|', '|', '|', '|', '|', '|', '|', '*', '|', '|'],
    ['|', '|', '|', '|', '|', '|', '|', '*', '|', '|'],
    ['|', '|', '|', '|', '|', '|', '|', '*', '*', '*'],
]

busqueda = ((x,  y) for x,  row in enumerate(laberinto)
                        for y,  elemento in enumerate(row)  if elemento == '*')

for e in busqueda:
    print(e)

Exit

(0, 0)
(0, 1)
(1, 1)
(1, 2)
(1, 3)
(2, 3)
(2, 6)
(2, 7)
(2, 8)
(3, 3)
(3, 6)
(3, 8)
(4, 3)
(4, 4)
(4, 5)
(4, 6)
(4, 8)
(4, 9)
(5, 9)
(6, 7)
(6, 8)
(6, 9)
(7, 7)
(8, 7)
(9, 7)
(9, 8)
(9, 9)

In this case a generator is created that returns a tuple with the indices of each element that is '*'.

We use two for to traverse the matrix, enumerate returns a tuple with the index and value for each element in the list.

If you want a list with all the indexes directly, you simply do:

busqueda = [(x,  y) for x,  row in enumerate(laberinto)
                        for y,  elemento in enumerate(row)  if elemento == '*']
    
answered by 13.10.2017 / 01:14
source