可以使用递归方法来按层级提取嵌套列表中的字符串。以下是一个代码示例:
def extract_strings(nested_list):
# 创建一个空列表,用于存储提取出的字符串
result = []
# 遍历嵌套列表中的每个元素
for item in nested_list:
# 检查元素的类型
if isinstance(item, str):
# 如果元素是字符串,则将其添加到结果列表中
result.append(item)
elif isinstance(item, list):
# 如果元素是列表,则递归调用该函数来提取嵌套列表中的字符串
result.extend(extract_strings(item))
return result
# 测试示例
nested_list = ['a', ['b', ['c', 'd'], 'e'], 'f', ['g', 'h']]
result = extract_strings(nested_list)
print(result)
输出结果为:['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
在这个示例中,extract_strings函数接受一个嵌套列表作为参数,并返回一个包含所有提取出的字符串的列表。函数使用递归来处理嵌套列表中的每个元素。如果元素是字符串,则将其添加到结果列表中。如果元素是列表,则递归调用extract_strings函数来提取嵌套列表中的字符串,并将返回的结果列表扩展到当前的结果列表中。最后,返回最终的结果列表。