Home > Enterprise >  python: locate elements in sublists
python: locate elements in sublists

Time:09-22

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

CodePudding user response:

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

lst=[['a', 'b', 'c', 'd', 'e'], ['f', 'g', 'h']]
def fnd_idx(char, lst):
    pos = []
    for x in range(len(lst)):
        try:
            idx = lst[x].index(char)
            pos = [x,idx]
            return pos
        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

CodePudding user response:

Try this function (just one line of code!):

def idx(lst, el):
    return next(((i, sublst.index(el))
                 for i, sublst in enumerate(lst)
                 if el in sublst),
                None)

So for example:

>>> idx(lst, 'a')
(0, 0)
>>> idx(lst, 'c')
(0, 2)

CodePudding user response:

lst=[['a', 'b', 'c', 'd', 'c'], ['f', 'g', 'h']]
searchvalue = 'f'
counter = 0
for index in lst:
    if searchvalue in index:
       print(counter, index.index(searchvalue))
    counter =1

CodePudding user response:

you can do this with numpy, the benefit is you don't have to hardcode anything for the size of nested lists. you can have hundreds or 3 and this will work!

lst=[['a', 'b', 'c', 'd', 'e'], ['f', 'g', 'h']]
arr = np.array(lst, dtype=object)

for x in arr:
    try:
        print (x.index('a'), x)
    except:
        pass
  • Related