我有一个列表:
[[21, 32, 32], [23, 34, 32], [32, 34, 57]]
我想将每个数字转换为自己的列表,如
[[[21], [32], [32]], [[23], [34], [32]], [[32], [34], [57]]]
我该怎么做?
谢谢!
答案 0 :(得分:1)
使用列表理解:
>>> lst = [[21, 32, 32], [23, 34, 32], [32, 34, 57]]
>>> new_lst = [[[i] for i in sub_lst] for sub_lst in lst]
>>> new_lst
[[[21], [32], [32]], [[23], [34], [32]], [[32], [34], [57]]]
您还可以使用numpy
,只需在切片数组时使用np.newaxis
添加额外的轴:
>>> import numpy as np
>>> l = np.array([[21, 32, 32], [23, 34, 32], [32, 34, 57]])
>>> l[:, :, np.newaxis] # or l[:, :, None]
array([[[21],
[32],
[32]],
[[23],
[34],
[32]],
[[32],
[34],
[57]]])
答案 1 :(得分:1)
以下是使用numpy.reshape()
的方法:
import numpy as np
arr = np.array([[21, 32, 32], [23, 34, 32], [32, 34, 57]])
arr.reshape(3,3,1)
# array([[[21],
# [32],
# [32]],
# [[23],
# [34],
# [32]],
# [[32],
# [34],
# [57]]])
答案 2 :(得分:0)
使用列表理解的方法:
a = [[21, 32, 32], [23, 34, 32], [32, 34, 57]]
print [[[element] for element in each] for each in a]
输出:
[[[21], [32], [32]], [[23], [34], [32]], [[32], [34], [57]]]