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

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

For instance:

>>> 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 to do this?

+4
source share
3 answers

If you really want a solution that deals with this to any depth, this is what 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: I just remember that in 2.x you want basestring to allow unicode strings - this solution is great for 3.x users.

+5
source

You can simply change the data structure and use the 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 do not double the location of U to the pad, and therefore

 >>> where["U"] (2, 0, 2) 
+4
source
 In [9]: def find(val,lis): ind=[(j,i,k) for j,x in enumerate(lis) for i,y in enumerate(x) \ for k,z in enumerate(y) if z==val] return ind[0] if ind else None ...: In [10]: find("H",alphabet) Out[10]: (0, 2, 1) In [14]: find("M",alphabet) Out[14]: (1, 1, 0) 
+3
source

All Articles