1

I have a complex structure array:

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]]]

that I want to convert like that:

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]]

I have already tried:

t.tolist()

but it doesn't work...

Ideas?

2 Answers 2

1

Just chain one level with 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)

Which removes one level:

[[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']]

If it is an actual array.array the logic is the same

Sign up to request clarification or add additional context in comments.

Comments

1

It is not a general solution but it should work in this case:

>>> 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]]

Note: I replaced the values in your list to make it reproducible.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.