我有一个复杂的结构数组:
t=[[[array([x1,y1,z1,i1,r1,g1,b1]),label1,ind1,dist1],
[array([x2,y2,z2,i2,r2,g2,b2]),label1,ind2,dist2],
[array([x3,y3,z3,i3,r3,g3,b3]),label1,ind3,dist3]],
[[array([x4,y4,z4,i4,r4,g4,b4]),label2,ind4,dist4],
[array([x5,y5,z5,i5,r5,g5,b5]),label2,ind5,dist5]]]
我希望像这样转换:
t=[[array([x1,y1,z1,i1,r1,g1,b1]),label1,ind1,dist1,
array([x2,y2,z2,i2,r2,g2,b2]),label1,ind2,dist2,
array([x3,y3,z3,i3,r3,g3,b3]),label1,ind3,dist3],
[array([x4,y4,z4,i4,r4,g4,b4]),label2,ind4,dist4,
array([x5,y5,z5,i5,r5,g5,b5]),label2,ind5,dist5]]
我已经尝试过了:
t.tolist()
但它不起作用......
想法?
答案 0 :(得分:1)
这不是一般解决方案,但它应该适用于这种情况:
>>> t = [[[array([1, 1, 1, 1, 1, 1, 1]), 1, 1, 1],
[array([2, 2, 2, 2, 2, 2, 2]), 1, 2, 2],
[array([3, 3, 3, 3, 3, 3, 3]), 1, 3, 3]],
[[array([4, 4, 4, 4, 4, 4, 4]), 2, 4, 4],
[array([5, 5, 5, 5, 5, 5, 5]), 2, 5, 5]]]
>>> newt = [[k for subsubt in subt for k in subsubt] for subt in t]
>>> print newt
[[array([1, 1, 1, 1, 1, 1, 1]),
1,
1,
1,
array([2, 2, 2, 2, 2, 2, 2]),
1,
2,
2,
array([3, 3, 3, 3, 3, 3, 3]),
1,
3,
3],
[array([4, 4, 4, 4, 4, 4, 4]),
2,
4,
4,
array([5, 5, 5, 5, 5, 5, 5]),
2,
5,
5]]
注意:我替换了列表中的值以使其可重现。
答案 1 :(得分:1)
只需使用itertools.chain链接一个级别:
t=[[[array(["x1","y1","z1","i1","r1","g1","b1"]),"label1","ind1","dist1"],
[array(["x2","y2","z2","i2","r2","g2","b2"]),"label1","ind2","dist2"],
[array(['x3','y3','z3','i3','r3','g3','b3']),'label1','ind3','dist3']],
[[array(['x4','y4','z4','i4','r4','g4','b4']),'label2','ind4','dist4'],
[array(['x5','y5','z5','i5','r5','g5','b5']),'label2','ind5','dist5']]]
from itertools import chain
t[:] = (list(chain.from_iterable(ele)) for ele in t)
from pprint import pprint as pp
pp(t)
删除一个级别:
[[array(['x1', 'y1', 'z1', 'i1', 'r1', 'g1', 'b1'],
dtype='<U2'),
'label1',
'ind1',
'dist1',
array(['x2', 'y2', 'z2', 'i2', 'r2', 'g2', 'b2'],
dtype='<U2'),
'label1',
'ind2',
'dist2',
array(['x3', 'y3', 'z3', 'i3', 'r3', 'g3', 'b3'],
dtype='<U2'),
'label1',
'ind3',
'dist3'],
[array(['x4', 'y4', 'z4', 'i4', 'r4', 'g4', 'b4'],
dtype='<U2'),
'label2',
'ind4',
'dist4',
array(['x5', 'y5', 'z5', 'i5', 'r5', 'g5', 'b5'],
dtype='<U2'),
'label2',
'ind5',
'dist5']]
如果它是实际的array.array
,则逻辑是相同的