如何将嵌套列表转换为单层列表

假设你有一个嵌套列表:

nested_list = [[1,2,3],[4,5,[6,7],8],[9,[10,11,[12,13,14]]]]

你需要将它转换为一个单层列表:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

可以使用以下方法实现:

方法一:递归

def flatten(nested_list):
    flat_list = []
    for item in nested_list:
        if isinstance(item, list):
            flat_list.extend(flatten(item))
        else:
            flat_list.append(item)
    return flat_list

flat_list = flatten(nested_list)
print(flat_list)  # 输出:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

方法二:列表推导式

flat_list = [item for sublist in nested_list for item in sublist]
print(flat_list)  # 输出:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

方法三:使用 itertools.chain.from_iterable

from itertools import chain

flat_list = list(chain.from_iterable(nested_list))
print(flat_list)  # 输出:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

以上三种方法都可以将嵌套列表转换为单层列表。选择哪种方法取决于你的代码风格和个人喜好。

如何将嵌套列表转换为单层列表

原文地址: https://www.cveoy.top/t/topic/mUT8 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录