写出一个`for`循环,遍历一个包含列表的列表(如`[[1, 2], [3, 4], [5, 6]]`),并将所有元素展开为一个新列表`[1, 2, 3, 4, 5, 6]`。

# 遍历包含列表的列表并将所有元素展开为一个新列表
nested_list = [[1, 2], [3, 4], [5, 6]]
flattened_list = []

for sublist in nested_list:
    for item in sublist:
        flattened_list.append(item)

print(flattened_list)  # 输出: [1, 2, 3, 4, 5, 6]

详细解释

  1. 问题背景: 我们有一个包含多个子列表的嵌套列表(如[[1, 2], [3, 4], [5, 6]]),需要将所有子列表中的元素展开为一个单一的列表[1, 2, 3, 4, 5, 6]。

  2. 解决思路:

    • 使用嵌套的for循环:外层循环遍历嵌套列表中的每个子列表,内层循环遍历子列表中的每个元素。
    • 将内层循环中的每个元素添加到一个新的列表中。
  3. 代码示例:

    • 定义嵌套列表nested_list。
    • 初始化一个空列表flattened_list用于存储展开后的元素。
    • 外层for循环遍历nested_list中的每个子列表sublist。
    • 内层for循环遍历子列表sublist中的每个元素item。
    • 通过flattened_list.append(item)将每个元素添加到新列表中。
  4. 变体示例: 如果希望对任意深度的嵌套列表展开,可以使用递归方法:

    def flatten_list(nested_list):
        flattened = []
        for item in nested_list:
            if isinstance(item, list):
                flattened.extend(flatten_list(item))
            else:
                flattened.append(item)
        return flattened
    
    nested_list = [[1, 2], [3, [4, 5]], [6]]
    print(flatten_list(nested_list))  # 输出: [1, 2, 3, 4, 5, 6]
    
  5. 总结:

    • 对于简单的两层嵌套列表,使用嵌套的for循环是最直观的解决方案。
    • 对于更复杂的嵌套结构,递归方法更加灵活。
    • 还可以使用Python标准库的itertools.chain来实现类似功能,但核心思想依然是遍历嵌套结构。