有多种方法可以将二维列表转换为一维列表。以下是几种常见的方法:

  1. 使用列表推导式:
two_dim_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
one_dim_list = [element for sublist in two_dim_list for element in sublist]
  1. 使用嵌套的for循环:
two_dim_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
one_dim_list = []
for sublist in two_dim_list:
    for element in sublist:
        one_dim_list.append(element)
  1. 使用itertools库中的chain函数:
import itertools
two_dim_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
one_dim_list = list(itertools.chain.from_iterable(two_dim_list))
  1. 使用numpy库的flatten函数:
import numpy as np
two_dim_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
one_dim_list = np.array(two_dim_list).flatten().tolist()

注意:在使用numpy库之前需要先安装它,可以使用pip install numpy命令进行安装。

这些方法可以将二维列表转换为一维列表,你可以根据自己的需求选择其中的一种方法。

Python 2D 列表转 1D 列表:多种高效方法详解

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

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