MST

星途 面试题库

面试题:Python for循环中如何高效处理嵌套数据结构

给定一个嵌套列表 `nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]`,请使用`for`循环将其扁平化,即转换为一个一维列表 `[1, 2, 3, 4, 5, 6, 7, 8, 9]`,并且要求尽可能高效,不能使用内置的`itertools`模块。
25.4万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened_list = []
for sublist in nested_list:
    for num in sublist:
        flattened_list.append(num)
print(flattened_list)