我想弄清楚如何在嵌套列表中獲取特定元素級別的計數(shù)。my_list = ["a", ["b", ["c", "d"], "e"], "f", ["g", ["h"]]]為了獲得元素“e”的級別,我試圖創(chuàng)建一個遞歸函數(shù)但失敗了......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))結(jié)果應(yīng)該是2。請讓我知道是否有任何辦法。
1 回答

ITMISS
TA貢獻1871條經(jīng)驗 獲得超8個贊
得到這樣的東西:
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))
添加回答
舉報
0/150
提交
取消