Rcoding
Rcoding

Reputation: 357

Count the depth of a specific element in a nested list

I am trying to figure out how to get the count of certain element's level in a nested list.

my_list = ["a", ["b", ["c", "d"], "e"], "f", ["g", ["h"]]]

To get the level of the element "e", I've tried to make a function for recursion but failed...

def get_level(letter, my_list):
    cnt = 0
    for sub_list in my_list:
        if letter in sub_list:
            cnt += 1
            return cnt
        else:
            get_level(letter, sub_list)

letter = "e"
print(get_level(letter, my_list))

The result should be 2.

Please let me know if there is any way for it.

Upvotes: 0

Views: 237

Answers (1)

Onilol
Onilol

Reputation: 1339

Got something like this:

def find_e(arr, index):
  if 'e' in arr:
    return index
  else:
    for element in arr:
      if isinstance(element, list):
        return find_e(element, index + 1)

my_list = ["a", ["b", ["c", "d"], "e"], "f", ["g", ["h"]]]
print('Index is: ',find_e(my_list, 0))

Upvotes: 1

Related Questions