Not sure if it is what you are after, however it appears that a simple recursive function can traverse the nested list - this is equivalent to a depth first search - we continue down each nested list in turn until we hit the bottom, come back up and continue down until we have traversed all lists and values
def traverse(nested_list):
results = []
for item in nested_list:
if isinstance(item, list):
results.append(traverse(item))
else:
if item == "LK":
val = 1
elif item == "SD":
val = 2
else:
val = None
results.append(val)
return results
This ignores the levels - so now we can count levels by passing them to the function
def traverse_with_levels(nested_list, level=0):
results = []
for item in nested_list:
if isinstance(item, list):
results.append(traverse_with_levels(item, level + 1))
else:
if item == "LK":
val = level + 1
elif item == "SD":
val = level + 2
else:
val = None
results.append(val)
return results
Finally we don’t start our counter until we hit the first match ‘LK’. There may be the edge case where there is only a list of 'SD’s
def traverse_with_levels_and_seen(nested_list, level=0, seen=False):
results = []
for item in nested_list:
if isinstance(item, list):
if seen:
level += 1
results.append(traverse_with_levels_and_seen(item, level, seen))
else:
if item == "LK":
seen = True
val = level + 1
elif item == "SD":
val = level + 2
else:
val = None
results.append(val)
return results
Unfortunately this will give different depths if there is a deeper nested list before a shallow one as the ‘seen’ is triggered lower - so it works on a per ‘branch’ basis and we would need to backtrack to fix the levels.
So finally to get the result I understand you are after, we need to traverse the list twice to get the first level of ‘LK’ and then process the result
def level_depth_helper(nested_list, level=0):
levels = []
for i in nested_list:
if isinstance(i, list):
levels.append(level_depth_helper(i, level + 1))
else:
if i == "LK":
levels.append(level)
return min(levels)
def traverse_with_levels_and_depth(nested_list, level=0, first_level=None):
# Test for depth
if not first_level:
first_level = level_depth_helper(nested_list)
results = []
for item in nested_list:
if isinstance(item, list):
results.append(traverse_with_levels_and_depth(item, level + 1, first_level))
else:
if item == "LK":
results.append(level + 1 - first_level)
elif item == "SD":
results.append(level + 2 - first_level)
else:
results.append(None)
return results