简体   繁体   中英

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.

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM