Python提取列表中TAG标签间嵌套子列表的代码问题排查
returnListBetweenTag Function to Group Elements Between 'TAG' Markers Let's break down what's going wrong with your current function and fix it to get the expected nested list output.
The Problem Recap
You have a source list:[2,3,5,'TAG',6,7,3,2,6,'TAG',9,9,8,3]
And you need to group elements between (and around) the 'TAG' markers into sublists, expecting:[[2,3,5], [6,7,3,2,6], [9,9,8,3]]
Your current function is outputting [[2, 3, 5], [6, 7, 3], [6, 'TAG', 9], [8, 3]], which means your grouping logic is misfiring—likely either not resetting temporary groups correctly when hitting a 'TAG', accidentally including 'TAG' in sublists, or splitting groups at the wrong points.
The Correct Implementation
Here's a revised version of the function that handles the grouping properly:
def returnListBetweenTag(input_list): final_groups = [] current_group = [] for item in input_list: if item == 'TAG': # Only add the current group to results if it's not empty if current_group: final_groups.append(current_group) # Reset the current group to start collecting the next set of elements current_group = [] else: # Add non-TAG elements to the current group current_group.append(item) # Don't forget the last group after the final TAG (or entire list if no TAGs exist) if current_group: final_groups.append(current_group) return final_groups
How This Works
Let's walk through the logic step by step:
- We initialize two lists:
final_groupsto hold our nested result, andcurrent_groupto collect elements as we iterate. - For each item in the input list:
- If we hit a
'TAG', we check ifcurrent_grouphas elements (to avoid adding empty lists). If it does, we add it tofinal_groupsand resetcurrent_groupto start fresh. - If the item isn't a
'TAG', we add it tocurrent_group.
- If we hit a
- After the loop finishes, we check if there's any leftover elements in
current_group(this covers the elements after the last'TAG'), and add it tofinal_groups.
Testing the Function
Let's run it with your test list to confirm:
test_list = [2,3,5,'TAG',6,7,3,2,6,'TAG',9,9,8,3] print(returnListBetweenTag(test_list)) # Output: [[2, 3, 5], [6, 7, 3, 2, 6], [9, 9, 8, 3]]
This matches exactly what you were expecting!
What Was Likely Wrong With Your Original Code
From the incorrect output you shared, it's probable that:
- Your function wasn't resetting
current_groupfully after hitting a'TAG', leading to partial groups being split. - It might have accidentally included
'TAG'in some sublists (like the[6, 'TAG', 9]entry in your output). - Or it was triggering a new group at the wrong time (like after a certain number of elements, instead of only on
'TAG'markers).
内容的提问来源于stack exchange,提问作者swing1234

