Jennifer Waddell
Jennifer Waddell

Reputation: 49

Python: How to find certain characters in nested list and return indexes

I am after a way to return a a tuple list of indexes of where these certain characters are.

For example, I want to know where in my nested list that I have blank spaces (" ").

Say I have this:

board = [
        ["a", " ", " "],
        [" ", "x", " "],
        [" ", "b", " "]
    ]

and my function will be:

def empty_squares(board):
"""Return a list of the empty squares in the board, each as
   a (row, column) tuple"""

So if I run the function it would return [(0,1), (0,2), (1,0), (1,2), (2,0), (2,2)].

I'm just not sure how to do this for nested lists.

Thank you!

Upvotes: 1

Views: 197

Answers (3)

mapf
mapf

Reputation: 2058

The easiest way is probably to use numpy.where().

import numpy as np


board = [
    ["a", " ", " "],
    [" ", "x", " "],
    [" ", "b", " "]
]

idxs = [(i, j) for i, j in zip(*np.where(np.array(board) == ' '))]
print(idxs)

Upvotes: 1

Paweł Kowalski
Paweł Kowalski

Reputation: 544

Maybe with enumerate?

board = [
        ["a", " ", " "],
        [" ", "x", " "],
        [" ", "b", " "]
    ]

def empty_squares(board, symbol):
    """
    Return a list of the empty squares in the board, each as
    a (row, column) tuple
    """
    empty = []
    for row, sublist in enumerate(board):
        for column, item in enumerate(sublist):
            if item == symbol:
                empty.append((row, column))
    return empty

>>> empty_squares(board, ' ')
[(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 2)]

Upvotes: 2

sander
sander

Reputation: 1440

You can loop over the board and use enumerate to keep track of the indexes.

l = []

for indexa, e in enumerate(board):
    for indexb, c in enumerate(e):
        if c == ' ':
            l.append((indexa, indexb))

Or simply with a list comprehension:

l = [(indexa, indexb) for indexb, c in enumerate(e) for indexa, e in enumerate(board) if c == ' ']

Both will output:

[(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 2)]

Upvotes: 3

Related Questions