Ben Specht
Ben Specht

Reputation: 5

Finding a string in a string in a list python

What I've got at the moment is a grid, which looks like this:

--d--
--d--
-d---
---d-
-d-d-

I'm trying to find the location of each 'd' within the grid. I am able to do this using a simple for loop, however I encounter a problem when I try to find the two 'd's on the same line, it only finds the first one and not the second one. However since it is in a list format (not 100% sure if I can change it out of that format) the .find() method will not work. Not sure if there's a simple way to solve this or if I need to completely re-think my approach but any help would be useful.

Code for the search that I've got at the moment(without the attempt to search for multiple occurrences as it broke everything)

Assume board is the grid mentioned earlier

dirtyCellLocations = []
for idx, row in enumerate(board):
    for letter in row:
        if letter == 'd':
            dirtyLocation = (idx, row.index('d'))
            dirtyCellLocations.append(dirtyLocation)

If you're interested the way the grid was formed is with this

board = [[j for j in raw_input().strip()] for i in range(5)]

Upvotes: 0

Views: 92

Answers (2)

m.wasowski
m.wasowski

Reputation: 6386

You need to enumerate both rows and columns. Using list comprehension it would look like this:

grid = """--d--
--d--
-d---
---d-
-d-d-""".splitlines()

print [ (i, [j for j, ch in enumerate(row) if ch == 'd']) 
    for i, row in enumerate(grid)]
# [(0, [2]), (1, [2]), (2, [1]), (3, [3]), (4, [1, 3])]

but this is a bit ugly, so you might extract inner comprehension into a function:

def get_dirties(row):
    return [i for i, ch in enumerate(row) if ch == 'd']

all_dirties = [(i, get_dirties(row)) for row in enumerate(grid)]

Upvotes: 0

Cory Kramer
Cory Kramer

Reputation: 118021

If you have a board like so

board = ['--d--',
         '--d--',
         '-d---',
         '---d-',
         '-d-d-']

You could do

for row in range(len(board)):
    for col, value in enumerate(board[row]):
        if value == 'd':
            print('[{},{}]'.format(row,col))

Output (formatted as [row, column])

[0,2]
[1,2]
[2,1]
[3,3]
[4,1]
[4,3]

This could be turned into a function too

def findIndices(board, x):
    l = []
    for row in range(len(board)):
        for col, value in enumerate(board[row]):
        if value == x:
            l.append([row,col])
    return l

>>> findIndices(board, 'd')
[[0, 2], [1, 2], [2, 1], [3, 3], [4, 1], [4, 3]]

Upvotes: 1

Related Questions