ziggz234
ziggz234

Reputation: 41

How to find position of letters in array of strings

I have a problem where I need to find where letters are in a matrix of strings. The input is: maze1=['*****','* * *','* G**','*D***','* ***']

The expected output is a tuple of the letters coordinates. For this example, the expected output is [(2,2),(3,1)]

Here is my code so far I run into a problem when checking if the element is a letter:

    treasure=[]
    for i in range(len(maze)):
        for j in range(len(maze)):
            if maze[i][j].lower().isAlpha():
                treasure[i] = maze[i][j]
    print(treasure)

Upvotes: 0

Views: 107

Answers (3)

Alain T.
Alain T.

Reputation: 42143

Assuming your maze has 5 columns:

[(p//5,p%5) for p,l in enumerate("".join(maze1)) if l.isalpha()]

returns:

[(2, 2), (3, 1)]

Upvotes: 0

mad_
mad_

Reputation: 8273

Using regex

import re
result=[]
maze1 =['*****','* * *','* G**','*D***','* ***']
for counter, value in enumerate(maze1):
    m=re.search('([a-zA-Z]+)',value)
    if m :
        result.append((counter, m.start()))

Output

[(2, 2), (3, 1)]

Upvotes: 0

inspectorG4dget
inspectorG4dget

Reputation: 113945

In [2]: maze1=['*****','* * *','* G**','*D***','* ***']                                                                                                                                                                                                                                                                 

In [3]: [(i,j) for i,s in enumerate(maze1) for j,char in enumerate(s) if char.isalpha()]                                                                                                                                                                                                                                
Out[3]: [(2, 2), (3, 1)]

Upvotes: 1

Related Questions