python教程,如何快速将list扁平化处理?多维变一维?
发布于 作者:苏南大叔 来源:程序如此灵动~
话说鉴于ndarray和list的强烈的亲属性,说完ndarray的扁平化处理后,本文说一下list的扁平化处理方案,需求依然是多维变一维。

苏南大叔的“程序如此灵动”技术博客,本文描述list类型数据扁平化处理的方案。测试环境:win10,python@3.11.0,numpy@1.24.2,pandas@1.5.3。
没有reshape/flatten
list没有.reshape()方法,也没有.flatten()方法。会直接报错。
a = [list("苏南大叔"), list("技术博客")]
print(a,type(a)) # [['苏', '南', '大', '叔'], ['技', '术', '博', '客']] <class 'list'>
b = a.reshape(-1)
d = a.flatten()
报错信息如下:
AttributeError: 'list' object has no attribute 'reshape'AttributeError: 'list' object has no attribute 'flatten'list扁平化【不推荐】
list扁平化操作,应该如何操作呢?
a = [list("苏南大叔"), list("技术博客")]
print(a,type(a)) # [['苏', '南', '大', '叔'], ['技', '术', '博', '客']] <class 'list'>
b= [y for x in a for y in x]
print(b,type(b)) # ['苏', '南', '大', '叔', '技', '术', '博', '客'] <class 'list'>关键代码:
[y for x in list_ for y in x]这是针对二维list的写法,如果换成了三维,依然需要加大for in的层级了。

ndarray曲线救国【推荐】
既然list天然不支持reshape()和flatten(),但是list和ndarray是可以互换的啊。所以,完全可以借助ndarray来曲线救国。参考文章:
测试代码:
import numpy as np
a = [list("苏南大叔"), list("技术博客")]
print(a, type(a)) # [['苏', '南', '大', '叔'], ['技', '术', '博', '客']] <class 'list'>
d = np.array(a).reshape(-1).tolist()
print(d, type(d)) # ['苏', '南', '大', '叔', '技', '术', '博', '客'] <class 'list'>关键代码:
np.array(list_).reshape(-1).tolist()或者:
np.array(list_).reshape(list_.size).tolist()或者:
np.array(list_).ravel().tolist()或者:
np.array(list_).flatten().tolist()或者:
np.array(list_).flatten(order='C').tolist()
numpy直接处理【推荐】
直接看代码:
import numpy as np
a = [["苏","南","大","叔"],["技","术","博","客"]]
b = np.ravel(a).tolist() # ['苏' '南' '大' '叔' '技' '术' '博' '客']
c = np.reshape(a,-1).tolist() # ['苏' '南' '大' '叔' '技' '术' '博' '客']
print(b,c)总结
list通过变身ndarray,从而获得了.flatten()扁平化的能力。更多python的相关文章: