可以使用递归来实现列表的扁平化。具体步骤如下:
以下是一个示例代码:
def flatten(lst):
result = []
for item in lst:
if isinstance(item, tuple):
result.extend(flatten(list(item))) # 递归调用扁平化函数
else:
result.append(item)
return result
# 测试代码
lst = [1, 2, [3, (4, 5), 6], 7, (8, [9, 10])]
result = flatten(lst)
print(result)
输出结果为:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
在这个示例中,输入的列表 lst
包含了嵌套的列表和元组。通过递归调用 flatten
函数,将列表扁平化为不包含嵌套结构的列表。