V S
V S

Reputation: 5

Reshape 2D tuple to 1D

I have a tuple (32 x 120):

example (4x120)


[ [1, 2, 3, 4, .... , 118, 119, 120],
  [2, 3, 4, 5, .... , 119, 120, 121],
  [3, 4, 5, 6, .... , 120, 121, 122], 
  [4, 5, 6, 7, .... , 121, 122, 123] ] 

and I want a vector like this :

[1,2,3,4, 2,3,4,5, 3,4,5,6, 4,5,6,7, ..... 118,119,120,121, 119,120,121,122, 120,121,122,123]

any idea?

Upvotes: 0

Views: 1487

Answers (2)

David Buck
David Buck

Reputation: 3842

A quick and easy way would be to do this in Numpy as you can simply transpose the array with T and then flatten() it into a 1D array.

import numpy as np
x = np.array([ [1, 2, 3, 4  118, 119, 120],
             [2, 3, 4, 5, 119, 120, 121],
             [3, 4, 5, 6, 120, 121, 122], 
             [4, 5, 6, 7, 121, 122, 123] ] )

print(x.T.flatten())

gives

array([  1,   2,   3,   4,   2,   3,   4,   5,   3,   4,   5,   6,   4,
         5,   6,   7, 118, 119, 120, 121, 119, 120, 121, 122, 120, 121,
       122, 123])

If you wanted it as a list rather than an array it would be x.T.flatten().tolist()

For a non-Numpy solution, you could use this:

[inner for outer in zip(*x) for inner in outer]

Which returns the same output as above.

Upvotes: 1

Paddy Harrison
Paddy Harrison

Reputation: 2012

You can use NumPy np.ravel to flatten an array.

Example using tuple of tuples (works for lists too):

import numpy as np
a = ((1,2,3), (2,3,4), (4,5,6))
np.ravel(a)

Gives an array where which is unravelled by appending the rows:

>>> array([1, 2, 3, 2, 3, 4, 4, 5, 6])

This can be done column wise as:

np.ravel(a, order='F')
>>> array([1, 2, 4, 2, 3, 5, 3, 4, 6])

Arrays can be converted to a list easily, eg:

np.ravel(a).tolist()
>>> [1, 2, 3, 2, 3, 4, 4, 5, 6]

Upvotes: 1

Related Questions