Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Index of item in a list of lists of lists (Python)

I am trying to find the index of a letter in the following list of lists of lists:

For example:

>>> alphabet = [[["A","B","C"],["D","E","F"],["G","H","I"]],[["J","K","L"],["M","N","O"],["P","Q","R"]],[["S","T","U"],["V","W","X"],["Y","Z","_"]]]
>>> find("H",alphabet)
(0,2,1)

What is the most Pythonic way of doing this?

like image 217
Harry E-W Avatar asked Dec 16 '22 15:12

Harry E-W


2 Answers

If you really want a solution that deals with this to any depth, this is the kind of thing you are looking for (as a simple recursive function):

def find_recursive(needle, haystack):
    for index, item in enumerate(haystack):
        if not isinstance(item, str):
            try:
                path = find_recursive(needle, item)
                if path is not None:
                    return (index, ) + path
            except TypeError:
                pass
        if needle == item:
            return index,
    return None

Edit: Just remembered, in 2.x, you want basestring to allow for unicode strings too - this solution is fine for 3.x users.

like image 197
Gareth Latty Avatar answered Dec 18 '22 03:12

Gareth Latty


You could simply change the data structure and use a dict:

>>> import itertools
>>> import string
>>> lets = string.ascii_uppercase
>>> where = dict(zip(lets, itertools.product(range(3), repeat=3)))
>>> where
{'A': (0, 0, 0), 'C': (0, 0, 2), 'B': (0, 0, 1), 'E': (0, 1, 1), 'D': (0, 1, 0), 'G': (0, 2, 0), 'F': (0, 1, 2), 'I': (0, 2, 2), 'H': (0, 2, 1), 'K': (1, 0, 1), 'J': (1, 0, 0), 'M': (1, 1, 0), 'L': (1, 0, 2), 'O': (1, 1, 2), 'N': (1, 1, 1), 'Q': (1, 2, 1), 'P': (1, 2, 0), 'S': (2, 0, 0), 'R': (1, 2, 2), 'U': (2, 0, 2), 'T': (2, 0, 1), 'W': (2, 1, 1), 'V': (2, 1, 0), 'Y': (2, 2, 0), 'X': (2, 1, 2), 'Z': (2, 2, 1)}
>>> where["H"]
(0, 2, 1)

but note that I don't double the locations of the U to pad, and so

>>> where["U"]
(2, 0, 2)
like image 42
DSM Avatar answered Dec 18 '22 05:12

DSM