转载,整理
嵌套列表的压平
如何将多维列表转化成一维的?
对于规范的且嵌套维度较低的多维列表,python中有很多方法可以实现:
1、简单的多维列表转化
a=[[1,2],[3,4],[5,6]]
print([j for i in a for j in i])
[1, 2, 3, 4, 5, 6]
#or
from itertools import chain
print(list(chain(*a)))
[1, 2, 3, 4, 5, 6]
#or
import itertools
a = [[1,2,3],[4,5,6], [7], [8,9]]
out = list(itertools.chain.from_iterable(a))
print(out)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
#or
a=[[1,2],[3,4],[5,6]]
t=[]
[t.extend(i) for i in a]
print(t)
type(t)
[1, 2, 3, 4, 5, 6]
#or
a=[[1,2],[3,4],[5,6]]
print(sum(a,[]))
[1, 2, 3, 4, 5, 6]
#or
from functools import reduce
reduce(lambda x, y: x+ y, a)
[1, 2, 3, 4, 5, 6]
2、复杂的多维列表转化
对于复杂的多维嵌套列表就需要使用一些复杂的方法:
train_ingredients = [[1],["123",1]]
old_list = list(train_ingredients)
new_list = []
for item in old_list:
for ingredient in item:
new_list.append(ingredient)
print(new_list)
[1, ‘123’, 1]
from sklearn import preprocessing
enc = preprocessing.OneHotEncoder() # 创建对象
enc.fit([[0,0,3],
[1,1,0],
[0,2,1],
[1,0,2]]) # 拟合,对每个列表中属性逐一编码,即第一个属性“0,1,0,1”,第二个属性“0,1,2,0”,第三个变量“3,0,1,2”
print(enc.n_values_) #每个feature所占位数
#feature_indices_ 是对 n_values_ 的累积值,不过 feature_indices 的首位是 0
print(enc.feature_indices_) #每个feature在新 One hot 编码下的索引位置
array = enc.transform([[0,1,3]]).toarray() # 转化
print(array)
# 前 2 位 1, 0,对 0 进行编码
# 中间 3 位 0, 1, 0 对 1 进行编码;
# 末尾 4 位 0, 1, 0, 0 对 1 进行编码;
[2 3 4]
[0 2 5 9] #每个feature所占位数
[[1. 0. 0. 1. 0. 0. 0. 0. 1.]] #每个feature在新 One hot 编码下的索引位置
参考:
【1】sklearn preprocessing 数据预处理(OneHotEncoder)https://blog.youkuaiyun.com/lanchunhui/article/details/72794317
【2】sklearn-OneHotEncoder https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html
【3】Python嵌套列表转一维(压平嵌套列表)https://blog.youkuaiyun.com/acmer_ding/article/details/73195260