Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: locate elements in sublists

given these sublists

lst=[['a', 'b', 'c', 'd', 'e'], ['f', 'g', 'h']]

I am trying to find the location of its elements, for instance, the letter 'a' is located at 0,0 but this line

print(lst.index('a'))

instead produces the following error: ValueError: 'a' is not in list

like image 229
john johns Avatar asked Nov 15 '22 18:11

john johns


1 Answers

if your list have depth=2, you can use this:

lst=[['a', 'b', 'c', 'd', 'e'], ['f', 'g', 'h']]
def fnd_idx(char, lst):
    for x in range(len(lst)):
        try:
            idx = lst[x].index(char)
            return [x,idx]
        except ValueError:
            pass
    return None

Output:

>>> print(fnd_idx('a', lst))
[0, 0]

>>> print(fnd_idx('g', lst))
[1, 1]

>>> print(fnd_idx('z', lst))
None
like image 178
I'mahdi Avatar answered Dec 04 '22 10:12

I'mahdi