Python: Finding All 'Section' Elements Under 'Unit 1' in Nested Lists
To find all 'Section' elements below 'Unit 1' in the given nested list structure using Python, you can use recursion. Here's an example code snippet:
def find_sections(data):
sections = []
for item in data:
if isinstance(item, list):
sections.extend(find_sections(item))
elif isinstance(item, str) and item.startswith('Section'):
sections.append(item)
return sections
# Nested list structure
data = [
'Unit 1',
[
'Text 1',
[
'Section 1',
[
'Text 2',
'Text 3'
]
],
'Section 2'
]
]
# Find all 'Section' below 'Unit 1'
sections = find_sections(data)
print(sections)
Output:
['Section 1', 'Section 2']
In this example, the find_sections function recursively traverses the nested list and checks each item. If the item is a list, it calls itself to search for sections inside that list. If the item is a string and starts with 'Section', it is considered a section and added to the sections list. Finally, it returns the list of sections found.
原文地址: https://www.cveoy.top/t/topic/pJwR 著作权归作者所有。请勿转载和采集!