请实现一个函数,将嵌套的列表展平为一个一维列表,同时处理任意深度的嵌套。例如输入`[1, [2, [3, 4], 5], 6]`,输出`[1, 2, 3, 4, 5, 6]`。

def flatten_list(nested_list):
    """
    将任意深度的嵌套列表展平为一个一维列表。
    
    :param nested_list: 嵌套的列表
    :return: 展平后的一维列表
    """
    flat_list = []
    for item in nested_list:
        if isinstance(item, list):
            # 递归处理嵌套列表
            flat_list.extend(flatten_list(item))
        else:
            flat_list.append(item)
    return flat_list

# 示例
nested_list = [1, [2, [3, 4], 5], 6]
print(flatten_list(nested_list))  # 输出: [1, 2, 3, 4, 5, 6]

方法解析

  1. 递归思想:
    • 函数会遍历输入的列表中的每一个元素。
    • 如果当前元素是一个列表,则递归调用flatten_list函数继续处理该子列表。
    • 如果当前元素不是列表,则直接将其添加到结果列表中。
  2. 逻辑清晰:
    • 通过递归的方式,可以处理任意深度的嵌套列表。
    • 使用isinstance(item, list)来判断元素是否为列表,避免数据类型错误。
  3. 性能优化:
    • 使用extend方法将递归结果直接拼接到结果列表中,避免多次创建临时列表,提高效率。

示例说明

# 示例1:普通嵌套
nested_list1 = [1, [2, [3, 4], 5], 6]
print(flatten_list(nested_list1))  # 输出: [1, 2, 3, 4, 5, 6]

# 示例2:更复杂的嵌套
nested_list2 = [1, [2, [3, [4, [5]]], 6], [7, 8]]
print(flatten_list(nested_list2))  # 输出: [1, 2, 3, 4, 5, 6, 7, 8]

# 示例3:空列表
nested_list3 = []
print(flatten_list(nested_list3))  # 输出: []

# 示例4:非嵌套列表
nested_list4 = [1, 2, 3]
print(flatten_list(nested_list4))  # 输出: [1, 2, 3]

边界情况处理

  1. 空列表:如果输入为空列表,函数会直接返回空列表。
  2. 非嵌套列表:如果输入已经是一个一维列表,函数会原样返回。
  3. 混合数据类型:如果列表中包含非列表和非数字的元素(如字符串、元组等),函数会跳过嵌套检查,直接将其添加到结果中。

进一步优化

  1. 生成器方式: 可以使用生成器来逐步生成展平后的元素,节省内存。
    def flatten_generator(nested_list):
        for item in nested_list:
            if isinstance(item, list):
                yield from flatten_generator(item)
            else:
                yield item
    
    nested_list = [1, [2, [3, 4], 5], 6]
    print(list(flatten_generator(nested_list)))  # 输出: [1, 2, 3, 4, 5, 6]
    
  2. 尾递归优化: 虽然Python默认不支持尾递归优化,但可以通过循环替代递归来避免栈溢出问题。
    def flatten_iterative(nested_list):
        stack = [iter(nested_list)]
        flat_list = []
        while stack:
            try:
                item = next(stack[-1])
                if isinstance(item, list):
                    stack.append(iter(item))
                else:
                    flat_list.append(item)
            except StopIteration:
                stack.pop()
        return flat_list
    
    nested_list = [1, [2, [3, 4], 5], 6]
    print(flatten_iterative(nested_list))  # 输出: [1, 2, 3, 4, 5, 6]
    

总结

通过递归或迭代的方式,可以高效地将任意深度的嵌套列表展平为一维列表。递归方法代码简洁,适合嵌套层数较少的情况;迭代方法性能更优,适合深层嵌套的列表。