Python - 将列表中的列转换为单独的元素


在使用 Python 分析或处理数据时,我们会遇到需要重塑或重新整理给定列表以获取具有不同列的列表的情况。我们可以通过下面讨论的多种方法来实现这一点。

使用切片

我们可以对列表在某些元素处进行切片以创建列结构。在这里,我们将给定的列表转换为一个新列表,其中元素从中间拆分。我们使用了两个 for 循环。外部循环将元素从第零个元素拆分到第二个元素,内部循环将元素从第二个元素拆分到最后一个元素。

示例

 实时演示

x = [[5,10,15,20],[25,30,35,40],[45,50,55,60]]
#Using list slicing and list comprehension
print ("The Given input is : \n" + str(x))
result = [m for y in [[n[2: ], [n[0:2]]] for n in x] for m in y]
print ("Converting column to separate elements in list of lists : \n" + str(result))

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

输出

运行以上代码,我们将得到以下结果:

The Given input is :
[[5, 10, 15, 20], [25, 30, 35, 40], [45, 50, 55, 60]]
Converting column to separate elements in list of lists :
[[15, 20], [[5, 10]], [35, 40], [[25, 30]], [55, 60], [[45, 50]]]

itertools.chain() 和列表推导式

除了使用两个 for 循环之外,我们还可以使用 itertools 中的 chain 方法。使用列表推导式,我们应用与上面相同的逻辑,并获得结果,其中列在给定列表的中间被拆分。

示例

 实时演示

from itertools import chain
x = [[5,10,15,20],[25,30,35,40],[45,50,55,60]]
#Using list slicing and list comprehension
print ("The Given input is : \n" + str(x))
res = list(chain(*[list((n[2: ], [n[0:2]]))
   for n in x]))
print ("Converting column to separate elements in list of lists : \n" + str(res))

输出

运行以上代码,我们将得到以下结果:

The Given input is :
[[5, 10, 15, 20], [25, 30, 35, 40], [45, 50, 55, 60]]
Converting column to separate elements in list of lists :
[[15, 20], [[5, 10]], [35, 40], [[25, 30]], [55, 60], [[45, 50]]]

更新于: 2020年2月26日

245 次查看

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告