[英]How to transpose a 3D list in python?
Let's say I have this matrix m
of dimensions 9 x 9 x 26: 假设我有一个尺寸为9 x 9 x 26的矩阵
m
:
[[['a00', ... 'z00'], ['a01', ... 'z01'], ... ['a09', ... 'z09']],
[['a10', ... 'z10'], ['a11', ... 'z11'], ... ['a19', ... 'z19']],
...
[['a90', ... 'z90'], ['a91', ... 'z91'], ... ['a99', ... 'z99']]]
I want to convert A to the following matrix of dimensions 26 x 81: 我想将A转换为以下尺寸为26 x 81的矩阵:
[['a00', 'a01', ... 'a09', 'a10', ... 'a19', ... 'a99'],
['z00', 'z01', ... 'z09', 'z10', ... 'z19', ... 'z99']]
What's the best way of doing this in python? 在python中执行此操作的最佳方法是什么?
Is this the kind of reordering you want? 这是您想要的重新排序吗?
In [128]: a=[[[11,12,13],[14,15,16]],[[21,22,23],[24,25,26]]]
In [129]: A=np.array(a)
In [130]: A
Out[130]:
array([[[11, 12, 13],
[14, 15, 16]],
[[21, 22, 23],
[24, 25, 26]]])
In [131]: A.reshape(-1,3).T
Out[131]:
array([[11, 14, 21, 24],
[12, 15, 22, 25],
[13, 16, 23, 26]])
A
is (2,2,3)
, and result is (3,4)
. A
是(2,2,3)
,结果是(3,4)
。
I reshaped it into (4,3)
, and then transposed the 2 axes. 我将其重塑为
(4,3)
,然后移置了2个轴。
Sometimes questions like this are confusing, especially if they don't have a concrete example to test. 有时,诸如此类的问题令人困惑,尤其是在没有具体示例可测试的情况下。 If I didn't get it right, I made need to apply the transpose first, with a full specification.
如果我做对了,我需要先应用转置,并使用完整的规范。
eg 例如
In [136]: A.transpose([2,0,1]).reshape(3,-1)
Out[136]:
array([[11, 14, 21, 24],
[12, 15, 22, 25],
[13, 16, 23, 26]])
If you have lists, as opposed an array, the task will be more difficult. 如果您有列表,而不是数组,那么任务将更加困难。 There is an easy idiom for 'transposing' a '2d' nested list, but it might not apply to '3d'.
有一个简单的习惯用法可以“转置”“ 2d”嵌套列表,但它可能不适用于“ 3d”。
In [137]: zip(*a)
Out[137]: [([11, 12, 13], [21, 22, 23]), ([14, 15, 16], [24, 25, 26])]
(ok, the other answer has the non-array solution). (好的,另一个答案是非数组解决方案)。
If you have a list and not a numpy array: 如果您有一个列表而不是一个numpy数组:
m = [[['a00', 'z00'], ['a01', 'z01'], ['a09', 'z09']],
[['a10', 'z10'], ['a11', 'z11'], ['a19', 'z19']],
[['a90', 'z90'], ['a91', 'z91'], ['a99', 'z99']]]
from itertools import chain
print zip(*(chain(*m))
[('a00', 'a01', 'a09', 'a10', 'a11', 'a19', 'a90', 'a91', 'a99'),
('z00', 'z01', 'z09', 'z10', 'z11', 'z19', 'z90', 'z91', 'z99')]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.